2

Consider the following class:

public class Extractor 
{

    public IService service;

    public Extractor(IService service) 
    {
        this.service = service;
    }

    public void DoSth() 
    {
        var sampleMethodInfo = this.service.GetMethodInfo();
        var version = ExtractAvailableMethodVersion(sampleMethodInfo);

        // other stuff
    }

    private int ExtractAvailableMethodVersion(MethodInfo methodInfo)
    {
        var regex = new Regex(MIGRATION_METHD_NAME_EXTRACT_VERSION);

        var matcher = regex.Match(methodInfo.Name);

        return Convert.ToInt32(matcher.Groups[1].Value);
    }
}

Resharper hints to make ExtractAvailableMethodVersion static. So my question is - should I make static method everywhere it's possible (like in the example ablove)? Is any performance difference when calling static / non-static method in such a case? Or is it only "code-style rule" to make static method when not using instance members?

8
  • 3
    static is very dangerous keyword. Commented Jul 2, 2014 at 6:58
  • Required reading: stackoverflow.com/questions/241339/… Commented Jul 2, 2014 at 7:00
  • I think resharper is suggesting this because it doesn't have any logic that involves an instance of Extractor, so static might be a viable option and save you from creating an instance purely for this method call. Commented Jul 2, 2014 at 7:01
  • 1
    @DhavalPatel I fear the kill keyword even more. Commented Jul 2, 2014 at 7:01
  • 1
    I also like this answer: stackoverflow.com/a/2671636/87088 Commented Jul 2, 2014 at 7:05

1 Answer 1

3

You don't make methods static just when possible, you do it when it makes sense, ie. what method does is not related to specific instance, but to a class in general.

Evaluate whether this is the case here, but you are not using current instance anywhere in the method, so above might be the case.

Sign up to request clarification or add additional context in comments.

Comments