Dejas
Dejas

Reputation: 3621

Why does this two line program NullPointerException?

class Program
{
    static void Main(string[] args)
    {
        Func<Object> someMethod = new Func<Object>(((Object)null).ToString);
        String nameOfMethod = someMethod.Method.Name;
    }
}

I'm not sure why the body of the someMethod function ever executes.

Upvotes: 0

Views: 203

Answers (3)

user530189
user530189

Reputation:

This code compiles to a ldnull followed by a ldvirtftn instruction. From ECMA-335 for ldvirtftn (4.18):

System.NullReferenceException is thrown if object is null.

You're not calling ToString, but the ldvirtftn instruction attempts to load the function pointer to ToString onto the evaluation stack. To do so, it needs a valid object reference.

Upvotes: 2

btlog
btlog

Reputation: 4780

(Object) null is still just null. You are trying to call null.ToString() which is why you are getting the NullPointerException.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160902

Func<Object> someMethod = new Func<Object>(((Object)null).ToString);

It's not executing, but you try to access the method ToString() on a null reference.

Upvotes: 5

Related Questions