andreasnico
andreasnico

Reputation: 1488

What happens when I cast null to another class

I have some code in a library method that looks like this:

public static WebDavProviderBase GetProvider(string relativePath)
{
  if (relativePath == null)
    return (WebDavProviderBase) null;
  if (relativePath.Length == 0)
    return (WebDavProviderBase) new DefaultProvider();
  WebDavProviderBase returnProvider = (WebDavProviderBase) null;
  if ((int) relativePath[0] == 47)
    relativePath = relativePath.Substring(1);
  WebDavProviderBase.GetRootProvider().MapPath(relativePath, out returnProvider);
  return returnProvider;
}

And when I use the code, it looks like this:

WebDavProviderBase provider = WebDavProviderBase.GetProvider(relativePath);

if (provider == null)
{
    //Do something
}

However, Resharper (10 Ultimate) complains about the null-check, and says this is a superfluous check, because provider can never be null.

Is Resharper wrong, or will (WebDavProviderBase)null return a new WebDavProviderBase?

Screenshot as requested: Provider can not be null message

UPDATE: After getting help from Jebs answer below, this is the conclusion: relativePath can not be null when GetProvider gets called, because the application will allready have crashed because of the relativePath.Lenght check further up in the code. (See screenshot)

Upvotes: 2

Views: 134

Answers (1)

autistic
autistic

Reputation: 15642

Let's start by addressing your concluding questions. There are two of them, merged into one (please try to avoid that), so I'll split them up and answer one at a time:

Is Resharper wrong...?

Yes. Well, maybe... More on that later.

... or will (WebDavProviderBase)null return a new WebDavProviderBase?

No.


Visual Studio 2015 Professional ... says this is a superfluous check, because provider can never be null.

This is perhaps only coincidentally connected to the question you asked, but it might be helpful to explain what I think is happening here anyway. VS2015 might be performing some form of deduction, inferring that when relativePath is non-null, the return value will also be non-null. There are two prerequisites here:

  • Can VS2015 deduce that relativePath is non-null, just by looking at the code you've written? If you've assigned that to a constant value, the answer is a definite "yes", for example. UPDATE: The .ToString() method is guaranteed to return a string or raise an exception, so the compiler can most likely deduce that relativePath is always non-null here.
  • Can VS2015 deduce that non-null relativePath values correspond to non-null GetProvider return values? This involves more complex functionality on behalf of the compiler, but it's not outside of the realm of compilation nonetheless... If the compiler can follow your logic and deduce that null can't possibly be returned, then it can safely tell you that your null checks are erroneous.

Upvotes: 3

Related Questions