C# possible null pointer exception [duplicate] - c#

Here is a piece of code:
IUser user = managerUser.GetUserById(UserId);
if ( user==null )
throw new Exception(...);
Quote quote = new Quote(user.FullName, user.Email);
Everything is fine here. But if I replace "if" line with the following one:
ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);
where function implementation is following:
public abstract class ComponentException<T> : ComponentException
where T : ComponentException, new()
{
public static void FailIfTrue(bool expression, string message)
{
if (expression)
{
T t = new T();
t.SetErrorMessage(message);
throw t;
}
}
//...
}
Then ReSharper generates me a warning: Possible 'System.NullReferenceException' pointing on 1st usage of 'user' object.
Q1. Why it generates such exception? As far as I see if user==null then exception will be generated and execution will never reach the usage point.
Q2. How to remove that warning? Please note:
1. I don't want to suppress this warning with comments (I will have a lot of similar pieces and don't want to transform my source code in 'commented garbage);
2. I don't want to changes ReSharper settings to change this problem from warning to 'suggestion' of 'hint'.
Thanks.
Any thoughts are welcome!
P.S. I am using resharper 5.1, MVSV 2008, C#

Resharper only looks at the current method for its analysis, and does not recursively analyse other methods you call.
You can however direct Resharper a bit and give it meta-information about certain methods. It knows for example about "Assert.IsNotNull(a)", and will take that information into account for the analysis. It is possible to make an external annotations file for Resharper and give it extra information about a certain library to make its analysis better. Maybe this might offer a way to solve your problem.
More information can be found here.
An example showing how it's used for the library Microsoft.Contracts can be found here.

A new answer in old post...
Here a little sample of my code regarding how to use CodeContract via ContractAnnotation with Resharper:
[ContractAnnotation("value:null=>true")]
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
It is very simple...if u find the breadcrumb in the wood. You can check other cases too.
Have a nice day

Q1: Because Resharper doesn't do path analysing. It just sees a possible null reference and flags that.
Q2: You can't without doing either of what you provided already.

You do know (or expect) that this code will throw an exception if there is a null reference:
ComponentException<MyUserManagerException>.FailIfTrue([...]);
However, since there is no contract specifying this, ReSharper has to assume that this is just a normal method call which may return without throwing any exception in any case.
Make this method implement the ReSharper contract, or as a simple workaround (which only affects debug mode, therefore no performance penalty for release mode), just after the FailIfTrue call:
Debug.Assert(user != null);
That will get rid of the warning, and as an added bonus do a runtime check in debug mode to ensure that the condition assumed by you after calling FailIfTrue is indeed met.

This is caused by the Resharper engine. These "possible NullReferenceException" happen because someone (probably at Resharper) has declared/configured somewhere an annotation on the method.
Here is how it works: ReSharper NullReferenceException Analysis and Its Contracts
Unfortunately, sometimes, these useful annotation are just wrong.
When you detect an error, you should report it to JetBrains and they will update the annotations on the next release. They're used to this.
Meanwhile, you can try to fix it by yourself. Read the article for more :)

Please check if you have any user==null if check above the given code. If there is, then ReSharper thinks that the variable "can be null" so recommends you to use a check/assert before referencing it. In some cases, that's the only way ReSharper can guess whether a variable can or cannot be null.

Related

How do I tell in c# codecontracts that a external method never returns null?

I have the following piece of c# code:
myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;
CodeContract knows that myClaimsIdentity is never null. But it complains that the FindFirst(string) method might return null:
Warning CodeContracts: Possibly calling a method on a null reference. Do you expect that System.Security.Claims.ClaimsIdentity.FindFirst(System.String) returns non-null?
I do expect this, but how can I tell it to the CodeChecker? Of course I can't change the the FindFirst(string) since it comes from an external library.
The simple approach is:
var nameIdentifier = myClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
Contract.Assume(nameIdentifier != null);
nameIdentifier.Value;
Code contracts will not try to prove the Assume condition, but will use it when proving other requirements.
It's probably possible to create a contract reference assembly for the external code which has the appropriate Ensures post-conditions. The code contracts team does this for the BCL types. But I don't know how to do that.

Resharper warns about a null string (System.NullReferenceException)

Just want to be sure that I haven't been coding for too long ... But, this seems highly unlikely :
http://i.imgur.com/TBjpNTX.png
I create the var, check for null, return if it is, so there's no way I can see it as being null at that point :)
Resharper bug ?
Edit:
As per Igal Tabachnik answer, he's right, I'm using the following method extension:
public static bool IsNullOrEmpty(this string target)
{
return String.IsNullOrEmpty(target);
}
I find it much easier to read
if (some_string.IsNullOrEmpty())
// do something here
rather than the:
if (string.IsNullOrEmpty(some_string))
// do something here
Solution:
Igal Tabachnik was right. The only 2 missing pieces were:
Resharper -> Options -> Code Annotations (under Code inspection group) -> turn on for solution.
Give VS a couple of minutes to get refresh everything.
Your code suggests that IsNullOrEmpty() method you're using is your own custom Extension method. The "real" IsNullOrEmpty is a static method of string.
Short answer: if you change it to
if (string.IsNullOrEmpty(input_string))
return "...";
ReSharper will stop complaining.
Long answer: Since this is your own extension method, ReSharper has no way of knowing how the result of this method applies to your code. For this, ReSharper uses code annotations to figure out additional information about the code. One such annotation is called a Contract Annotation, and it is what ReSharper uses to figure out the result of the original string.IsNullOrEmpty() method. You can read more about it in the blog post.
Bottom line, if you want to use your own extension method, but have ReSharper understand it correctly, you have to apply the following Contract Annotation on it:
[ContractAnnotation("null=>true")]
public static bool IsNullOrEmpty(this string input)
{
...
}
Your IsNullOrEmpty()-method seems to be an own invention since the original one is a static method of System.String and not an extension method. ReSharper isn't able to figure that one out though if you use the original one it will see that no null-values can make it past.
var str = value as string;
if (string.IsNullOrEmpty(str))
return;
var unicorn = str.Contains("unicorn");

Uses for [Obsolete(string, bool)] attribute for .NET

Note: I already checked msdn, it doesn't address my actual question, see below.
I'm trying to use the obsolete attribute on a (obviously obsolete) constructor in one of my classes. Here's the scenario:
I want to be able to force the developer to update to the new constructor without affecting already existing and deployed code. This way I can deploy my code to production just fine, but from a developers perspective, whenever they go into their code, instead of just getting a "warning" which I'm sure they'll just ignore, I want them to get a compile error because the status quo is no longer ok.
So my question is, will this affect only developers, or all calling apps, or do I have the whole thing wrong?
sample code:
public class MyClass
{
private string _userID; //new code
[Obsolete("This constructor is obsolete, please use other constructor.", true)]
public MyClass()
{
_userID = ""; //defaulting to empty string for all those using this constructor
}
public MyClass(string userID)
{
_userID = userID; //this is why they need to use this constructor
}
}
Any and all help will be appreciated, thanks in advance!
Yes, this primarily affects the compiler - any pre-built code won't be affected... unless that code explicitly checks for this attribute. For example, some serialization code (XmlSerializer, IIRC) checks for this - so it might not be entirely side-effect free... but in principal existing code won't usually be affected until they try to compile next.
Of course, if you are using this code from something that uses dynamic compilation (for example ASP.NET without pre-compile) then all bets are off.
The attribute is only an instruction to the compiler. Already existing binaries can still use the constructor.
So my question is, will this affect only developers, or all calling apps, or do I have the whole thing wrong?
This will only be used at compile time, by the compiler. It will not affect applications which have already been deployed.
As such, this will have the behavior you are trying to accomplish.
This is what [Obsolete] already does, no extra help is needed. It is not a compile time warning, it generates an error:
error CS0619: 'ConsoleApplication1.MyClass.MyClass()' is obsolete:
'This constructor is obsolete, please use other constructor.'

In C#, how do I keep certain method calls out of the codebase entirely?

I'm trying to get rid of all DateTime.Now method calls and replace them with my own GetNow() method, which may sometimes return a fixed date for testing purposes.
How can I enforce that no one adds a DateTime.Now call in the future? Can I use NDepend or StyleCop to check this on my continuous integration server?
With NDepend it is very easy to write this rule:
// <Name>Forbid DateTime.Now, use xxx.GetNow() instead</Name>
WARN IF Count > 0 IN
SELECT METHODS WHERE
IsDirectlyUsing "OPTIONAL:System.DateTime.get_Now()"
Notice:
The prefix WARN IF Count > 0 IN that transforms the CQL query into a rule
The way the property is referenced through the string System.DateTime.get_Now()
The prefix OPTIONAL that means "Don't emit a compilation error if the property get_Now is not found". This makes sense since if your code doesn't use anymore get_Now(), it is not anymore referenced from NDepend analysis.
Also, to generate the original query...
SELECT METHODS WHERE
IsDirectlyUsing "OPTIONAL:System.DateTime.get_Now()"
...just right-click DateTime.get_Now() and choose Select methods ... that are directly using me
Firstly, DateTime.Now is a property.
That means you don't need to put parenthesis after call.
Secondly, if by testing purposes you mean a framework like NUnit, you might want to check out Microsoft Moles which allows you to substitute any static method call with your own custom implementation while testing. Heck, it's cool:
[Test]
[ExpectedException (typeof (Y2KBugException))]
public void TestY2KBug ()
{
MDateTime.NowGet = () => new DateTime (2001, 1, 1);
Bomb.DetonateIfY2K ();
}
public static class Bomb {
public static void DetonateIfY2K ()
{
if (DateTime.Now == new DateTime (2001, 1, 1))
throw new Y2KBugException (); // take cover!
}
}
There's no real way to enforce something like this.
The closest you're going to come is making a custom FxCop rule or custom Visual Studio Code Analysis rule to error/warn on calls to DateTime.Now.
You could use Moles in your tests to provide your own DateTime.Now when required, without the need to modify any existing code that calls it.
Another option might be to modify the assembly after compilation to call something else. (Perhaps, use Mono.Cecil to rewrite the IL, and add a command to the post-build in VS to run it.)
You could perhaps grab the Mono source and build yourself a custom mscorlib with the function removed.
One approach might be to add a pre-commit hook to your source control repository of choice to look for DateTime.Now and abort the check-in if you find the offending string. It's not foolproof and it might be annoying to your colleagues but it should help keep it out of the codebase.
I don't think that this is possible. What you are actually trying to do is override DateTime's struct functionality.
The only way I can think of is just to go with a custom class that will wrap common functionality of DateTime and offer different functionality on demand...

Resharper and Code Contracts not playing well together

I'm using Resharper 5.x to do compile-time analysis and it's usually pretty good about it, but it doesn't seem to be applying code contracts to its logic. I have something like the following, but I'm getting an issue on the marked line.
public void Method(int arg)
{
Contract.Requires(this.NullableValueType != null);
this.Method2(
arg,
this.NullableValueType.Value, // [1]
this.ReferenceType);
}
[1] ends up getting highlighted with "Possible 'System.InvalidOperationException'". Is there a way to get rid of this error without turning off the check?
While admittedly Resharper could be more intelligent and take contracts into account, unfortunately currently it doesn’t.
I would recommend to make the line more explicit. Instead of
this.NullableValueType.Value
you could write
this.NullableValueType ?? <something>
where the “something” is, of course, something that doesn’t matter because it never happens (for example, new ThatValueType()).

Categories