Static Methods in C# .NET

Static Methods in C# .NET

If all you want is an easy way to set up a few methods, and call them at will, you can set up a class filled with public static methods.
Static methods don't need an object. So you don't do this to create them:
MyClass object_name = new MyClass( )
Instead, you just call them when needed. Let's see how.
From the C# menu bar at the top, click Project > Add Class. Call your new class stats. Type the following code between the curly brackets of your new class:
public static int addUp(int num1, int num2)
{

return num1 + num2;
}
The only thing here that's different from a normal Method is the use of the word static. Note that it comes after public but before int. You can use any of the other variables types as well, such asstatic string, or static bool, etc.
Add a button to your form, and double click to get at the code.
To use the static Method in your new class, the syntax is just this:
class_name.method_name( )
Because it's a static method, you don't have to go to the bother of setting up a new object - your method will available straight away.
Add the following code to you button to try it out:
string answer;
answer = stats.addUp( 5, 4 ).ToString();
MessageBox.Show(answer);
The class name stats will appear on the IntelliSense menu without you having to do anything else. And when you type a dot after your class name, the static method will appear on the list.
There's an awful lot to static members, obviously. For example, you can create static fields, static properties, and even static constructors. But if you want a class filled with methods that you want quick access to, then just use static methods.


We'll leave classes now and move on. But if you want to get grips with C# .NET, especially if you want a career as a programmer, then classes are something you need to study.

Comments