EDIT: This is not a duplicate of this question as this one is a practical example working with Delegate.CreateDelegate and the other one is a theoretical discussion about IL. Nothing to do one with each other besides the words this and null.
Relative to this question ...
I have a situation when an event handler is called on an instance that is null. Weird. Look at the image:
I do not understand what is happening. How an instance method can be called on a null instance???
equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .
In computer programming, null is both a value and a pointer. Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C.
In Java, a variable is a reference to an object. A null value thus indicates an unset reference (i.e. a reference to nothing). You can see variables as containers(*), inside which you can put an object of a given type, when the variable is null , it means your container is empty.
The way you typically represent a “missing” or “invalid” value in C# is to use the “null” value of the type. Every reference type has a “null” value; that is, the reference that does not actually refer to anything.
You can create this case using the Delegate.CreateDelegate overload where you provide a null
reference for the target of invocation.
class Foo { public void Method() { Console.WriteLine(this == null); } } Action<Foo> action = (Action<Foo>)Delegate.CreateDelegate( typeof(Action<Foo>), null, typeof(Foo).GetMethod("Method")); action(null); //prints True
From the MSDN remarks on that page:
If firstArgument is a null reference and method is an instance method, the result depends on the signatures of the delegate type type and of method:
•If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.
•If the signatures of method and type match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.
So it's documented as a known, and probably intended, behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With