Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does constructor returns null?

Tags:

c#

I'm writing C# program, and VisualStudio's VSTO wizard generates below code.

private static string GetResourceText(string resourceName)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    string[] resourceNames = asm.GetManifestResourceNames();
    for (int i = 0; i < resourceNames.Length; ++i)
    {
        if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
        {
            using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
            {
                if (resourceReader != null)
                {
                    return resourceReader.ReadToEnd();
                }
            }
        }
    }
    return null;
}

I think if (resourceReader != null) is redundant, because constructor always returns not null. Isn't it?

like image 629
unarist Avatar asked Jan 13 '23 07:01

unarist


2 Answers

In regular sane code, a constructor will not return null. There are some convoluted ways you can force a constructor to return null, but it is such a bizarre edge case that you will never see it. To all intents and purposes: new on this object will never return null - and it is completely pointless to add a null-check after a new(), especially for something sensible like StreamReader.

A simple case where you can get null:

object obj = new int?()

But this is simply exposing the subtle boxing behavior of nullable types. The more complicated way of getting a contructor to return null requires evil:

static void Main() {
    var obj = new MyFunnyType(); // wow! null!
}

class MyFunnyProxyAttribute : ProxyAttribute {
    public override MarshalByRefObject CreateInstance(Type serverType) {
        return null;
    }
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }
like image 113
Marc Gravell Avatar answered Jan 22 '23 14:01

Marc Gravell


According to ReSharper:

if (resourceReader != null)

Expression is always true

That's because the StreamReader constructor will never return null. In fact, I can't think of any time off my head where a constructor would ever return null.

like image 41
mattytommo Avatar answered Jan 22 '23 12:01

mattytommo