Can object constructor return a null?

前端 未结 5 1014
伪装坚强ぢ
伪装坚强ぢ 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: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 - i.e.

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

    This is a slightly bigger problem with generics:

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

    (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.

提交回复
热议问题