Possible null reference with string?

Hello!

I noticed that ReSharper tells me when a NullReference exception may occur, prompting to check for null. However, it does not prompt me when I work with strings. Why is so?


public string MyTest(string inp) { return inp.Trim(); }


Isn't it true that passing will lead to NullReference exception (http://www.developersdex.com/csharp/message.asp?p=1111&r=6653166 etc.)?
(I normally use my simple TrimSafe() extension method, which checks for null before applying Trim(). )

1 comment

Hello,

I noticed that ReSharper tells me when a NullReference exception may
occur, prompting to check for null. However, it does not prompt me
when I work with strings. Why is so?

public string MyTest(string inp) { return inp.Trim(); }


This string is supposed to be "neutral", i.e. R# does not know for sure neither
that it can never be null nor that it's valid to pass null in here. Displaying
warnings for all "neutral" reference type variables will overload the code
with warnings, many of them being false alerts.

If you specify that the parameter is allowed to be null by contract, you'll
get the warnings.

public string MyTest( string inp) { return inp.Trim(); }

There're such annotations for all the standard .NET libraries, that's why
you can get the warnings (where appropriate) when working with their return
values or passing variables to them.

See R# Options / Code Inspection / Code Annotations / Copy... for sample
annotation attribute declarations.


Serge Baltic
JetBrains, Inc — http://www.jetbrains.com
“Develop with pleasure!”


0

Please sign in to leave a comment.