CSharp - Add static method to a non static class

Introduction

A non-static class can contain static methods.

The following program has a non-static class that contains a static and a non-static method.

Demo

using System;

class NonStaticClass
{
    //a static method
    public static void StaticMethod()
    {//  w  w w. j  ava2s  . c om
        Console.WriteLine("NonStaticClass.StaticMethod");
    }
    //a non-static method
    public void NonStaticMethod()
    {
        Console.WriteLine("NonStaticClass.NonStaticMethod");
    }
}

class Program
{
    static void Main(string[] args)
    {
        NonStaticClass anObject = new NonStaticClass();
        anObject.NonStaticMethod();//Ok
                                   //anObject.StaticMethod();//Error
        NonStaticClass.StaticMethod();
    }
}

Result

Related Topic