About
In this code snippet, we will learn about the static keyword in C#.
The static keyword is used to indicate that a method, property, etc can be used without making an instance of its class.
Let’s see how to use the static keyword in the code below.
Code:
using System; namespace Static { class Program { static void Main(string[] args) { //MyMethod can't be called without an insatnce of MyClass. //MyMethod(); MyClass MC = new MyClass(); MC.MyMethod(); //MyOthermethod is static so it can be called without an instance of MyClass. MyClass.MyOtherMethod(); Console.ReadLine(); } } class MyClass { public void MyMethod() { Console.WriteLine("From MyMethod."); } public static void MyOtherMethod() { Console.WriteLine("From MyOtherMethod."); } } }