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?

  • 3
    static is very dangerous keyword. – Dhaval Patel Jul 02 '14 at 06:58
  • Required reading: http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp – User999999 Jul 02 '14 at 07: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. – Sayse Jul 02 '14 at 07:01
  • 1
    @DhavalPatel I fear the `kill` keyword even more. – Uwe Keim Jul 02 '14 at 07:01
  • 1
    I also like this answer: http://stackoverflow.com/a/2671636/87088 – Saber Jul 02 '14 at 07:05
  • @Sayse - yes, but take a look that method is used only in one method and what's more - it's private, so there won't be a need to create instance only for a method call. :) Anyway - thanks, I will look closely at refrenced questions. –  Jul 02 '14 at 07:12
  • @pwas - you have provided a cut down example, its impossible to know how many times its called :) – Sayse Jul 02 '14 at 07:13
  • @DhavalPatel how can you say `static` is a dangerous keyword? It's more restrictive, let's you do less things, so by definition it's less dangerous than NOT being static. I think what you mean is that "global mutable state accessed in secret by lying apis is dangerous". – sara May 19 '16 at 07:18

1 Answers1

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.

user3613916
  • 232
  • 1
  • 10