Hi there,

Today, I had a chat my lecturer about instance methods and static methods. I thought you make methods with static modifier (let me know in the comments below if I'm wrong) if you want to access them without creatng an instance of the class which they're defined in.

I found in C# if you're creating static methods, you won't be able to access them using the keyword 'this'. But you can still have access to instance methods through the 'this' word.

Is there any difference between those types of methods?

Recommended Answers

All 4 Replies

You're right, for an instance method you have to declare an instance of the class it is defined in as below:

Form1 myForm = new Form1();    

public Mainform()
{
    this.myForm.PopulateComboBoxe(this.myComboBox);
}

and for static methods you DON'T need to declare and instance of the class that the method is declared in:

public MainForm()
{
    Form1.PopulateComboBox(this.myComboBox);
}

It means you can just access that one aspect of the class without having to create an entire instance of the class and have to do all the messing around that comes with it (i.e. passing in values to set it the instance).

It's useful to make your generic methods static (like a comboBox population method) which you just need to pass in a stored proc name.

Thanks for that. I think I was right. I thought there is a bit more to it than that. The interesting thing that I found when you have static methods is they don't appear when you use the keyword this. Let's you've got this:

public MyClass{


    public MyClass(){
     this.RingMe();  // OK

     this.CallMe();   // not ok because you can't use the keyword this to call static methods

     CallMe();    // OK
    }

    public static void CallMe(){

    }


    public void RingMe(){

    }
} 

Is this similar to Java and AS3 and PHP? Anyone know?

I don't know, but I do know the this keyword of C# is a feature C# took over from Java. Just like C# took over lot of syntax from the C programming language family.

@ddanbe you're right I was always told if you can you can use Java it would be easy to transfer to C# because of how similar.

C# sharp is just a highter level language than the other members of the C family, it automates more of the complex tasks like memory management and it's syntax is generaly closer to natural language sp it's easier to understand.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.