Home >Backend Development >C++ >What Are Some Unexpected Behaviors and Corner Cases in C# and .NET?
Explore the strange corners of C# and the .NET framework
In software development, we often encounter some puzzling edge cases. This article will explore some of the most bizarre edge cases in C# and the .NET framework, revealing their anomalous behavior.
String resident exception
Consider the following code snippet:
<code class="language-csharp">string x = new string(new char[0]); string y = new string(new char[0]); Console.WriteLine(object.ReferenceEquals(x, y));</code>
Intuitively, we would expect the output to be False since the "new" keyword usually allocates space for a new object. Surprisingly, this code outputs True in all framework versions tested. Although the specification states that new objects should always be created, this becomes a special case.
Nullable type exception
This code further illustrates the complexity of C#:
<code class="language-csharp">static void Foo<T>() where T : new() { T t = new T(); // ... (其他操作) // 此行引发NullReferenceException Console.WriteLine(t.GetType()); }</code>
The mystery lies in type T. To uncover it, we have to examine the code carefully. The Nullable<T>
structure represents a nullable value type, which overrides most member methods, but does not override GetType()
. So when GetType()
is called, the nullable value is cast to object
(resulting in null), resulting in NullReferenceException
.
Class instantiation trick
Another puzzling edge case occurs in the following code, where T is restricted to a reference type:
<code class="language-csharp">private static void Main() { CanThisHappen<MyFunnyType>(); } public static void CanThisHappen<T>() where T : class, new() { var instance = new T(); Debug.Assert(instance != null, "我们是如何破坏CLR的?"); }</code>
Through excellent engineering design, this code can be broken using indirect methods similar to remote calls:
<code class="language-csharp">class MyFunnyProxyAttribute : ProxyAttribute { // ... (重写) } [MyFunnyProxy] class MyFunnyType : ContextBoundObject { }</code>
By defining a custom proxy attribute and redirecting the new()
call to return null, the assertion in CanThisHappen
is broken, demonstrating the tremendous flexibility and potential pitfalls in the C# language and .NET runtime.
The above is the detailed content of What Are Some Unexpected Behaviors and Corner Cases in C# and .NET?. For more information, please follow other related articles on the PHP Chinese website!