Can object constructor return a null?

前端 未结 5 996
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 19:32

We have taken over some .NET 1.1 Windows Service code that spawns threads to read messages off a queue (SeeBeyond eGate JMS queue, but that is not important) and in turn spa

相关标签:
5条回答
  • 2020-12-30 19:45

    You can make it appear like an object ctor returns null:

    http://seattlesoftware.wordpress.com/2008/03/05/returning-null-from-a-class-constructor/

    Search for "Another pattern which I haven’t seen used allows an invalid object to emulate a null reference" and read from there.

    0 讨论(0)
  • 2020-12-30 19:48

    Edit: for clarification there is an insane edge case where you can get null from a class constructor, but frankly I don't think any real code should ever expect to deal with this level of crazy: What's the strangest corner case you've seen in C# or .NET? . To all normal intents : it won't happen.


    No, you can't get null from a class constructor (Thread is a class). The only case I know of where a constructor can (seem to) return null is Nullable<T> - i.e.

    object foo = new int?(); // this is null
    

    This is a slightly bigger problem with generics:

    static void Oops<T>() where T : new() {
        T t = new T();
        if (t == null) throw new InvalidOperationException();
    }
    
    static void Main() {
        Oops<int?>();
    }
    

    (of course, there are ways of checking/handling that scenario, such as : class)

    Other than that, a constructor will always either return an object (or initialize a struct), or throw an exception.

    0 讨论(0)
  • 2020-12-30 19:49

    As core mentions, operator overloading can make it appear that a constructor returned null, when that's not what really happened. The authors of the article core found say they haven't seen it used, but it actually is used in a very popular product: Unity.

    This will compile and log a message at run time:

    using UnityEngine;
    
    public class Test:MonoBehaviour
    {
        void Start()
        {
            AudioSource as = new AudioSource();
    
            if (as == null)
            {
                Debug.Log("Looks null to me.");
            }
        }
    }
    

    Now, the fault here is mine, because one should not call the AudioSource constructor directly. But one should know that the == operator is overloaded at the root of the inheritance tree for the objects Unity can reference. Here's what the Unity manual says about UnityEngine.Object's == operator:

    Be careful when comparing with null.

    e.g.

    GameObject go = new GameObject();
    Debug.Log (go == null); // false
    
    Object obj = new Object();
    Debug.Log (obj == null); // true
    

    Instatiating a GameObject adds it to the scene so it's completely initialized (!destroyed). Instantiating a simple UnityEngine.Object has no such semantics, so the(sic) it stays in the 'destroyed' state which compares true to null.

    While instantiating a GameObject initializes it, instantiating an AudioSource object doesn't, so the comparison with null returns true.

    This unusual idiom is made even more stealthy by virtue of the fact that attempts to reference properties of the uninitialized AudioSource object will throw null-reference exceptions, which I initially misinterpreted as meaning the object reference was null, not the property.

    Others have answered the OP's question, but I wanted to add this answer because the OP's code might actually make sense if the Thread class therein isn't the one we would expect it to be, just as Object (and its descendants) isn't quite what you might expect it to be in a Unity script (that is, it is actually UnityEngine.Object, rather than System.Object, which gets you the overloaded == operator that so confused me).

    0 讨论(0)
  • 2020-12-30 19:55

    In my opinion, what the else statement suggests is that the previous developers didn't know their C#. A constructor always returns a constructed object or throws an exception.

    In the very old times, C++ constructors could return null, so maybe the problem comes from that. This is no longer true in C++ either, at least for the default new operator.

    0 讨论(0)
  • 2020-12-30 19:57

    NO! that null check is redundant. Lot of C++ devs who moved to C# have this habit of a null check and I guess it is the same here.

    The only thing is you should check the documentation to see if the constructor can throw any exception. In your case refer to http://msdn.microsoft.com/en-us/library/xx3ezzs2.aspx and as mentioned the constructor will always return a valid obj.

    0 讨论(0)
提交回复
热议问题