C# Static Keyword

C# Code Snippets Static Keyword
Share:

About

In this code snippet, we will learn about the static keyword in C#.

The static keyword is used to indicate that a methodproperty, 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.");
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger