Jasmeet
Jasmeet

Reputation: 1460

How to call a method from same class in another method in C#?

Now I am working with c# code that looks something like this

public class MyClass
{
    public static void Method1()
    {
        //Do something
    }

    public void Method2()
    {
        //Do something
        Method1();
    }
}

Now what if I replace the code as:

public class MyClass
{
    public static void Method1()
    {
        //Do something
    }

    public void Method2()
    {
        //Do something
        MyClass.Method1();
    }
}

Now what is the difference in above 2 representations. Is it the same or does it show some different working. Any help is appreciated.

Upvotes: 0

Views: 3580

Answers (2)

Rahul
Rahul

Reputation: 77926

Inside the class there is no difference but the difference comes when you try to invoke them from outside the class. For instance method you need a instance of your class whereas for static method that's not required. But inside your class you can just say

public class MyClass
{
    public static void Method1()
    {
        //Do something
    }

    public void Method2()
    {
        Method1();  //you don't have to qualify it
    }
}

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250336

The second is just a longer version of the previous. If you are in the same class as the static method, you do not need to specify the class name, you can, but you don't need to (much like specifying this for instance methods).

Upvotes: 4

Related Questions