Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)</p> <pre><code> static void Foo&lt;T&gt;() where T : new() { T t = new T(); Console.WriteLine(t.ToString()); // works fine Console.WriteLine(t.GetHashCode()); // works fine Console.WriteLine(t.Equals(t)); // works fine // so it looks like an object and smells like an object... // but this throws a NullReferenceException... Console.WriteLine(t.GetType()); } </code></pre> <p>So what was T...</p> <p>Answer: any <code>Nullable&lt;T&gt;</code> - such as <code>int?</code>. All the methods are overridden, except GetType() which can't be; so it is cast (boxed) to object (and hence to null) to call object.GetType()... which calls on null ;-p</p> <hr> <p>Update: the plot thickens... Ayende Rahien threw down a <a href="http://ayende.com/Blog/archive/2009/11/25/can-you-hack-this-out-hint-1.aspx" rel="nofollow noreferrer">similar challenge on his blog</a>, but with a <code>where T : class, new()</code>:</p> <pre><code>private static void Main() { CanThisHappen&lt;MyFunnyType&gt;(); } public static void CanThisHappen&lt;T&gt;() where T : class, new() { var instance = new T(); // new() on a ref-type; should be non-null, then Debug.Assert(instance != null, "How did we break the CLR?"); } </code></pre> <p>But it can be defeated! Using the same indirection used by things like remoting; warning - the following is <strong>pure evil</strong>:</p> <pre><code>class MyFunnyProxyAttribute : ProxyAttribute { public override MarshalByRefObject CreateInstance(Type serverType) { return null; } } [MyFunnyProxy] class MyFunnyType : ContextBoundObject { } </code></pre> <p>With this in place, the <code>new()</code> call is redirected to the proxy (<code>MyFunnyProxyAttribute</code>), which returns <code>null</code>. Now go and wash your eyes!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload