Concept of Static class, Non Static Class and method in C#

Amatya
Posted by Amatya under C# category on | Points: 40 | Views : 553
Concept of Static class, Non Static Class and method in C#
static void Main(string[] args)
{
Console.WriteLine(StaticAmatya.Var1);
Console.WriteLine(StaticAmatya.Var1);
Console.WriteLine(StaticAmatya.Var1);
Console.WriteLine(StaticAmatya.Var1);

NonStaticAmatya nsa = new NonStaticAmatya();
NonStaticAmatya nsa1 = new NonStaticAmatya();
NonStaticAmatya nsa2 = new NonStaticAmatya();
NonStaticAmatya nsa3 = new NonStaticAmatya();
//int b = nsa.Var2;
// Console.WriteLine(nsa.Var2);
Console.WriteLine(NonStaticAmatya.Var2);
Console.ReadLine();
}
static class StaticAmatya
{
public static int Var1;
static StaticAmatya()
{
++Var1;

}

}
public class NonStaticAmatya
{
public static int Var2;
public NonStaticAmatya()
{
++Var2;
}
}


Output:
1
1
1
1
4

Comment: As StaticAmatya is static class so the control will go only once in static class StaticAmatya() { }
while in NonStaticAmatya() { } the control will go 4 times as the instance is created i.e. nsa, nsa1, nsa2, nsa3


Thanks
Amatya

Comments or Responses

Login to post response