-1

In C#, why when we can define a class method and access to a method by class name directly, we should/some people define an object instead and then create an instance of that object?

Class1:

class Class1
{
    public static int PrintX(int x)
    {
        return x;
    }
    private int y;
    public int PrintY(int z)
    {
        return this.y = z;
    }
}

Main Method:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Class1.PrintX(9));

        Class1 newClass = new Class1();
        Console.WriteLine(newClass.PrintY(9));
    }
}

Both ways print out 9. Why should I use an object method and then create an instance of it?!

Reza Mas
  • 13
  • 3
  • 2
    This should help: http://stackoverflow.com/questions/2080150/when-should-i-use-static-methods-in-a-class-and-what-are-the-benefits – Some guy Oct 30 '15 at 18:39

1 Answers1

0

If you have to ask the question, then you shouldn't (use an object method). However, if you create two classes, they will affect each other.

Class1 newClassA = new Class1();
Class1 newClassB = new Class1();

Console.WriteLine(newClassA.PrintY(1));
Console.WriteLine(newClassB.PrintY(9));

After this code, newClassA's y is 9.

ergonaut
  • 6,929
  • 1
  • 17
  • 47