8

Let's say I have a class

public class product
{
    public string GetName()
    {
        return "product";
    }

    public static string GetStaticName()
    {
        return "product";
    }
 }

These methods do the same thing but one is static and one isn't.

When i call these method I do this:

product p = new product();
string _ProductName = p.GetName();

and

string _ProductName = product.GetStaticName();

Which method is the best to use for performance etc?

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69

1 Answers1

7

Which method is the best to use for performance etc?

You haven't to address any performance issue here. You just have to decide if this method should be the same for all the instances of the objects you create. If the answer is yes, then it should be a static method. Otherwise, it should be an instance method. It's a design decision, not a performance decision.

By the way, based on your code. I don't think that in this case you have to address even that. You just want to get the name of the product and probably set it. That being said the following is the only thing you need.

public class Product
{
    public string Name { get; set; }
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • But is there a difference in performance the way I call them in my example? If there is, which one? – Marcus Höglund Feb 26 '16 at 09:56
  • Marcus, getting the design right is MUCH more important here than any possible performance difference. If your code is running slowly, you need to profile it and find out why. It won't be because you did or did not use static methods. – Polyfun Feb 26 '16 at 10:07
  • @MarcusH You are welcome ! I am glad that I helped. – Christos Feb 26 '16 at 10:26