Within a C# instance method, can 'this' ever be null?

前端 未结 6 771
栀梦
栀梦 2020-12-17 08:30

I have a situation where very rarely a Queue of Objects is dequeuing a null. The only call to Enqueue is within the class itself:

m_DeltaQueue.Enqueue(this);         


        
6条回答
  •  一生所求
    2020-12-17 09:06

    (Slightly off-topic and a highly unlikely possibility; have made this community wiki. The real question has already been resolved; this is mainly related to the title of the question.)

    In theory, if your code m_DeltaQueue.Enqueue(this) resulted in the invocation of an implicit conversion operator on the argument, that could indeed result in a null-reference being passed to the method.

    class Foo
    {
        public static implicit operator string(Foo foo)
        {
            return null;
        }
    
        void InstanceMethod()
        {
            string @this = this;
    
            if (@this == null)
                Console.WriteLine("Appears like 'this' is null.");
        }
    
        static void Main()
        {
            new Foo().InstanceMethod();
        }
    }
    

提交回复
热议问题