Static implement in C#

What is static?

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used to declare static classes. In classes, interfaces, and structs, you may add the static modifier to fields, methods, properties, operators, events, and constructors. The static modifier can't be used with indexers or finalizers.

Note:-
  • static members default value is 0.
  • static functions are called only class name, no object are create.

1. Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingConsoleApplication
{
   class Program
    {
        static int i;
        public static void show()
        {
            Console.WriteLine(i);
        }
        static void Main(string[] args)
        {
            Program.show();
            Console.ReadLine();
        }
    }
}

Output

0

2. Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingConsoleApplication
{
   class Program
    {
        static float _pi;
        static float _radius;
        public static void setdata(float pi,float radius)
        {
            Program._pi = pi;
            Program._radius = radius;
        }
        public static void show()
        {
            float s = _pi * _radius * _radius;
            Console.WriteLine("Your result is " + s);
        }
        static void Main(string[] args)
        {
            Program.setdata(3.14f, 2.12f);
            Program.show();
            Console.ReadLine();
        }
    }
}

Output

Your result is 14.11242


Write a comment


Name Email Message