43

I have the method shown below which is generating a CA1822 Code Analysis warning. CA1822 says this:

"The 'this parameter (or 'Me' in Visual Basic) of 'ImportForm.ProcessFile(StreamReader)' 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."

Can anyone tell me why I am getting this warning, since the 'reader' parameter is in fact being used?

private void ProcessFile(StreamReader reader)
{
   string[] lines;

   lines = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

   ParseFile.IVAFile(lines);
}

5 Answers 5

56

It means you use no members of the object. All the items in the method come from the parameters.

Therefore the method can safely be made static.

22

"reader" is being used, but you're not using "this" anywhere, so you can make the method static.

The only reason not to make it static would be if you want to use polymorphism later - e.g. making it virtual and overriding it elsewhere.

5

Maybe I have found malicious behavior of this message.

In a Situation like

void Print()
{
    Console.Writeline(GetType().Name);
}

I get this CA1822 reported, although GetType() is an instance method. However, I found some Explanation, why GetType() is actually not a virtual method, not an instead method, and technicly behaving like a static method.

It's just that the code Analysis does not consider this special behavior.

1
  • 1
    Have you tried forcing this.GetType().Name? Does that remove the warning?
    – II ARROWS
    Mar 15, 2016 at 9:42
4

The warning occurs because you don't use any member variables of that class in that method. E.g.

this.m_anyVariable = anyValue;

Therefore you can/should mark that method as static.

2
  • 16
    Why should the method be marked as static? What's the benefit?
    – Bob Horn
    Dec 1, 2011 at 15:30
  • 17
    Ahh, because of performance. From MSDN: "After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
    – Bob Horn
    Dec 1, 2011 at 15:32
2

I think it is trying to tell you that this method can be made static.

The only thing this method needs to access is "reader", but nothing from the class instance to which it belongs ("this"). In which case, you can safely make it static.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.