Reputation: 4175
I run Code Analysis and got this message:
CA1822 : Microsoft.Performance : The 'this' parameter (or 'Me' in Visual Basic) of 'CreateIntervalString(TimeSpan)' is never used. Mark the member as static (or Shared in Visual Basic) or use 'this'/'Me' in the method body or at least one property accessor, if appropriate.
My code is:
private string CreateIntervalString(TimeSpan timeSpan)
{
return timeSpan.ToString();
}
as I understood, because CreateIntervalString
function does not use any the members of the class, and only uses on the timeSpan input, VisualStudio recommends me to mark it as static.
My Questions:
Thanks a lot!
Examples:
the following method provides an error:
private string CreateIntervalString(TimeSpan timeSpan)
{
return timeSpan.ToString();
}
and the following does not:
private DateTime ParseDateString(string dateTimeString)
{
// the years,monthe,days,hours,minutes and secondes found by the dateTimeString input
return new DateTime(years, months, days, hours, minutes, secondes);
}
Upvotes: 3
Views: 8462
Reputation: 1569
The MSDN site http://msdn.microsoft.com/en-us/library/ms245046.aspx gives the answer to the performance aspect
If the method is not marked as static then the current object (this) will be checked against null by the runtime. In most cases there will be little observable difference, it's true, but if a method which is called millions of times per second can get that gain by being made static then it could be worthwhile.
Upvotes: 8
Reputation: 14757
Hope that helps, John
Upvotes: 1
Reputation: 700342
The performance is not improved (in any way that matters), but the code gets clearer. The method doesn't make the impression that it uses the instance, and you can use the method without creating an instance of the class.
As you are not using the instance from the method, it doesn't affect the status of thread safety. As the method only uses the data that is sent to it, it is thread safe.
Either you actually use some instance member in the methods, there is something in the code that could potentially use some instance member, or there is something in the code that makes the tool think that it does.
Upvotes: 7
Reputation: 65126
this
argument), so theoretically they are somewhat more efficient.Upvotes: 3