Exploring Unexpected Behaviors in C# and .NET
Building robust applications requires a deep understanding of edge cases. C# and .NET, while powerful, present some surprising scenarios that challenge common assumptions. Let's examine a few examples illustrating these unusual behaviors:
When new
Doesn't Produce a New Object
Consider this seemingly straightforward code:
<code class="language-csharp">string x = new string(new char[0]); string y = new string(new char[0]); Console.WriteLine(object.ReferenceEquals(x, y)); // Prints True</code>
One might expect new
to always create distinct objects for reference types. However, C#'s special handling of empty strings leads to x
and y
referencing the same object.
Nullable Types and the NullReferenceException
This code snippet highlights a puzzling interaction with nullable types:
<code class="language-csharp">static void Foo<T>() where T : new() { T t = new T(); Console.WriteLine(t.GetType()); // Throws NullReferenceException }</code>
Even though t
is initialized, calling GetType()
throws a NullReferenceException
. This is because if T
is a nullable type (like int?
), the implicit boxing to object
can result in a null value, causing the exception when GetType()
is called on the boxed null.
The Case of the Null new
Instance
This scenario demonstrates a less intuitive possibility:
<code class="language-csharp">public static void CanThisHappen<T>() where T : class, new() { var instance = new T(); // new() on a ref-type; should be non-null Debug.Assert(instance != null, "How did we break the CLR?"); }</code>
The constraints suggest T
is a reference type instantiable with new
. However, techniques like remoting (e.g., using a proxy that returns null) can bypass this expectation, leading to the assertion failing. This highlights the complexities introduced when dealing with advanced features like remoting.
The above is the detailed content of Why Do Some C# and .NET Corner Cases Defy Expectations?. For more information, please follow other related articles on the PHP Chinese website!