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");
Related
I encountered the following code string in a project's code:
var result = string.Format(source);
with variable 'source' being a string
I can't understand what useful this line is doing. As I always thought, we need at least two parameters for string.Format method to have some useful output.
ReSharper is not highlighting this as a something redundant so it seems that this line might have some purpose which I can't grasp at the moment. (Or maybe ReSharper just doesn't handle this case specifically)
Why would one want to use string.Format with only one parameter?
Perhaps the overloaded function
public static string Format(string format, params object[] args);
is allowing that code to compile. I cann't imagine that string.Format(source) would be helping in any meaningful way.
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.
I'm getting this message from ReSharper. ReSharper is not proposing the change that I think would be appropriate after examining the code. As a result I am concerned that the problem might might be my not understanding what's going on instead of ReSharper not being as helpful as it could be.
public interface IFrobable { }
public class DataClass
{
public List<IFrobable> Frobables {get; set;}
//...
}
public class WorkerClass
{
//...
void Frobinate(List<IFrobable> frobables)
{
//Frobs the input
}
void DoSomething(List<IFrobable> input>)
{
//Original code with Resharper on OfType<IActivity>
Frobinate(input.OfType<IFrobable>().ToList());
//Suggested change from ReSharper - Is this a generic refactor
//instead of issue specific?
Frobinate(Enumerable.OfType<IFrobable>(input).ToList());
//What I think should be safe to do - compiles and appears to work
Frobinate(input);
}
}
Is there any reason why my proposed change might not be safe.
This is a regular function call:
Enumerable.OfType<IFrobable>(input)
This is the same function but invoked as an extension method:
input.OfType<IFrobable>()
In your case:
Frobinate(input);
Is absolutely fine because:
input.OfType<IFrobable>().ToList()
Equals to:
input.Where(x => x as IFrobable != null).ToList()
And in you method input is already defined as List<IFrobable> so what's the point?
Your last case may or may not introduce a logic error.
Do you really want Frobinate the ability to modify the input list passed into DoSomething or just a copy of those references?
//Suggested change from ReSharper
Actually, invoking OfType as a static method on Enumerable rather than as an extension method on input is not a suggestion from ReSharper - it's a context action. I expound on the difference in this post.
To the actual issue:
The inspection
Redundant 'IEnumerable.OfType<T>' call. Consider comparing with 'null' instead
is not one that ReSharper offers a quick fix solution with, I guess since there isn't a single unambiguously 'correct' change to make. It's just saying
hey, everything in input is definitely going to be of type IFrobable - if you're trying to filter this list you might have meant to be filtering by nullness instead
This probably isn't relevant in your case.
As to your proposed fix - as already noted, this will mean passing the actual List<> reference given to DoSomething to Frobinate, rather than a new List<> containing the same items - if this is OK, then go for it.
in your example you have input which already consists of elements of type IFrobable so ReSharper says that it doesn't make sense to filter them by type IFrobable because the filter condition is always true it proposes you to use just input.ToList() invocation or to filter elements buy nullness: input.Where(element => element != null).ToList()
I have written a method below like this:
internal static IList<EmpowerTaxView> GetEmpowerTaxViewsByLongAgencyAndAgencyTaxTypes(
IList<EmpowerCompanyTaxData> validEmpowerCompanyTaxDatas,
IList<EmpowerTaxView> empowerTaxViews)
{
IList<EmpowerTaxView> result = new List<EmpowerTaxView>();
foreach (EmpowerCompanyTaxData empowerCompanyTaxData in validEmpowerCompanyTaxDatas)
{
IList<EmpowerTaxView> validEmpowerTaxViews =
GetEmpowerTaxViewsByLongAgencyAndTaxType(
empowerCompanyTaxData, empowerTaxViews);
validEmpowerTaxViews.ToList().ForEach(delegate(EmpowerTaxView etv)
{
result.Add(etv);
});
}
return result;
}
And for this method, the resharper says:
validEmpowerTaxViews.ToList().ForEach(delegate(EmpowerTaxView etv)
{
result.Add(etv);
});
Convert to Method Group. What does this mean and what should be done to get rid of this.
What Resharper means is that you can express the ForEach code more simply by using the method group Add.
Example:
validEmpowerTaxViews.ToList().Foreach(result.Add);
The method group defined by Add is compatible with the delegate expected by ForEach and hence the C# compiler will take care of doing the conversion. The default in Resharper is to prefer method groups over lambdas and explicit delegate creation statements.
JaredPar already provided the correct answer, I just wanted to suggest a simpler implementation of the method:
internal static IList<EmpowerTaxView> GetEmpowerTaxViewsByLongAgencyAndAgencyTaxTypes(
IList<EmpowerCompanyTaxData> validEmpowerCompanyTaxDatas,
IList<EmpowerTaxView> empowerTaxViews)
{
var results =
from empowerCompanyTaxData in validEmpowerCompanyTaxDatas
from etv in GetEmpowerTaxViewsByLongAgencyAndTaxType(
empowerCompanyTaxData, empowerTaxViews)
select etv;
return results.ToList();
}
Accept Resharper's suggestion to see what changes it makes. You can always undo them.
If you aren't happy with the change and don't want Resharper suggesting it in future then you can disable that specific option - the others will remain available. See the answer here for details.
Resharper: vars
From Microsoft website Method group is a set of overloaded methods resulting from a member lookup
You can check inspecting MSIL code that if you use the method group then it just makes a new delegate pointing to that method.
But if you use a lambda expression then it generates a class with anonymous method under the hood. The result is that method group is required less memory then lambda and Resharper suggests you to optimize
The first parameter to a C# extension method is the instance that the extension method was called on. I have adopted an idiom, without seeing it elsewhere, of calling that variable "self". I would not be surprised at all if others are using that as well. Here's an example:
public static void Print(this string self)
{
if(self != null) Console.WriteLine(self);
}
However, I'm starting to see others name that parameter "#this", as follows:
public static void Print(this string #this)
{
if(#this != null) Console.WriteLine(#this);
}
And as a 3rd option, some prefer no idiom at all, saying that "self" and "#this" don't give any information. I think we all agree that sometimes there is a clear, meaningful name for the parameter, specific to its purpose, which is better than "self" or "#this". Some go further and say you can always come up with a more valuable name. So this is another valid point of view.
What other idioms have you seen? What idiom do you prefer, and why?
I name it fairly normally, based on the use. So "source" for the source sequence of a LINQ operator, or "argument"/"parameter" for an extension doing parameter/argument checking, etc.
I don't think it has to be particularly related to "this" or "self" - that doesn't give any extra information about the meaning of the parameter. Surely that's the most important thing.
EDIT: Even in the case where there's not a lot of obvious meaning, I'd prefer some meaning to none. What information is conferred by "self" or "#this"? Merely that it's the first parameter in an extension method - and that information is already obvious by the fact that the parameter is decorated with this. In the example case where theStringToPrint/self option is given, I'd use outputText instead - it conveys everything you need to know about the parameter, IMO.
I name the variable exactly how I would name it if it were a plain old static method. The reason being that it can still be called as a static method and you must consider that use case in your code.
The easiest way to look at this is argument validation. Consider the case where null is passed into your method. You should be doing argument checking and throwing an ArgumentNullException. If it's implemented properly you'll need to put "this" as the argument name like so.
public static void Print(this string #this) {
if ( null == #this ) {
throw new ArgumentNullException("this");
}
...
}
Now someone is coding against your library and suddenly gets an exception dialog which says "this is null". They will be most confused :)
This is a bit of a contrived example, but in general I treat extension methods no different that a plain old static method. I find it makes them easier to reason about.
I have seen obj and val used. I do not like #this. We should try to avoid using keywords. I have never seen self but I like it.
I call it 'target', since the extension method will operate on that parameter.
I believe #this should be avoided as it makes use of the most useless language-specific feature ever seen (#). In fact, anything that can cause confusion or decrease readability such as keywords appearing where they are not keywords should be avoided.
self reminds me of python but could be good for a consistent naming convention as it's clear that it's referring to the instance in use while not requiring some nasty syntactic trickery.
You could do something like this...
public static void Print(this string extended)
{
if(extended != null) Console.WriteLine(extended);
}