0

I have been looking on stackoverflow, but do not see the ansswer yet. Note: that I did see some good responses in C++, but not C#.

Is there any benefit in checking for null if (reader == null) as below, or will issues causing it to be null already cause an exception making if (reader == null) unreachable (with reader == null being true)?

try
{
    var reader = new PhotoReader();
    if (reader == null)
    {
        throw new InvalidOperationException("PhotoReader could not be created.");
    }
}
catch (Exception ex)
{
    // let user know failed object creation, etc.
    <...>
}
Buck
  • 599
  • 7
  • 20
  • 1
    CodeCaster regarding duplicate: That is great. I just did not see it from my search criteria. Please point me to the duplicate and I will check it out. Thank you. – Buck May 24 '14 at 19:31
  • CodeCaster: Just let me know if I should delete this even though it has answers. Difference in title may cause this to come up in searches versus the other. Thanks! – Buck May 25 '14 at 11:21

2 Answers2

5

No, there is no way you get null as result of contructor call in c#.

Constructor may throw an exception itself, but it will break your execution flow anyway.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

The fact that you instantiate reader by assigning the result of a class's constructor means that it will never be null, so that check is unnecessary.

adv12
  • 8,443
  • 2
  • 24
  • 48