Search code examples
c#c#-4.0thisil

Can "this" be null in C# virtual methods? What happens with the rest of instance methods?


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.


Solution

  • It's not standard C# but, further to the answers from Lasse and Jon, with a bit of IL-fiddling you can make a non-virtual call (to either virtual or non-virtual methods) passing a null this:

    using System;
    using System.Reflection.Emit;
    
    class Test
    {
        static void Main()
        {
            CallWithNullThis("Foo");
            CallWithNullThis("Bar");
        }
    
        static void CallWithNullThis(string methodName)
        {
            var mi = typeof(Test).GetMethod(methodName);
    
            // make Test the owner type to avoid VerificationException
            var dm = new DynamicMethod("$", typeof(void), Type.EmptyTypes, typeof(Test));
            var il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Call, mi);
            il.Emit(OpCodes.Ret);
    
            var action = (Action)dm.CreateDelegate(typeof(Action));
            action();
        }
    
        public void Foo()
        {
            Console.WriteLine(this == null ? "Weird" : "Normal");
        }
    
        public virtual void Bar()
        {
            Console.WriteLine(this == null ? "Weird" : "Normal");
        }
    }