Click here to Skip to main content
15,886,676 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,
I'm just refactoring some old code using ReSharper and it's suggested I change this:

var fileinfo = new FileInfo(file);
if(fileinfo != null)
{
}


to this:

var fileinfo = new FileInfo(file)
if(true)
{
}


I'm not sure I get this, I'm having a stupid moment but what is this actually evaluating? The lack of explicit reference to an object has confused me a bit.

Thanks,

Jammer
Posted

Assigning a new object to a variable almost always means that the variable is non-null, which makes the if evaluation meaningless. If creating an object like this might fail, the proper way is to use a static method along the lines of
C#
var fileinfo = FileInfo.CreateNew(file);
 
Share this answer
 
Comments
Daniel Grunwald 26-Nov-10 15:17pm    
To clarify: "almost always" means "always except in a weird case related to COM interop". There's no way "new" returns null in pure C# code.
Jammer 26-Nov-10 15:33pm    
Thanks for this ...

Jammer
I'm with you on this.
  1. if (true) is pretty silly.
  2. What if some day, someone will insert fileinfo=null; between the two lines?

:)
 
Share this answer
 
Comments
fjdiewornncalwe 26-Nov-10 18:06pm    
At that point Resharper will tell you to put the null reference check back in... LOL!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900