Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a class to call a method or use static methods? [duplicate]

Tags:

c#

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?

like image 438
Marcus Höglund Avatar asked Feb 26 '16 09:02

Marcus Höglund


1 Answers

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; }
}
like image 79
Christos Avatar answered Sep 21 '22 00:09

Christos