I was curious if there is a way for this
to be null in a virtual method in C#. I assume it is not possible. I saw that in existing code, during a code review and I would like to be 100% sure to comment for its removal, but I would like some confirmation and some more context from the community. Is it the case that this != null
in any non-static / instance method? Otherwise it would have been a null pointer exception right? I was thinking of extension methods and such or any C# feature that I could possibly be not familiar with coming from years of Java.
It's not possible to do this in normal C# (i.e. calling a method or property in a normal way), regardless of whether the method is virtual or not.
For non-virtual methods, you can create a delegate from an open instance method, effectively treating the instance method as a static method with a first parameter with the target type. You can invoke that delegate with a null argument, and observe this == null
in the method.
For a virtual method, you'd have to call the method non-virtually - which can happen with a call such as base.Foo(...)
... but I'm not sure whether there's any way of making that sort of non-virtual call with a null argument. The delegate approach definitely doesn't work here.
Demo code:
using System;
class Test
{
static void Main()
{
Action<Test> foo = (Action<Test>)
Delegate.CreateDelegate(typeof(Action<Test>), typeof(Test).GetMethod("Foo"));
foo(null); // Prints Weird
Action<Test> bar = (Action<Test>)
Delegate.CreateDelegate(typeof(Action<Test>), typeof(Test).GetMethod("Bar"));
bar(null); // Throws
}
public void Foo()
{
Console.WriteLine(this == null ? "Weird" : "Normal");
}
public virtual void Bar()
{
Console.WriteLine(this == null ? "Weird" : "Normal");
}
}
See more on this question at Stackoverflow