Advertisement



< Prev
Next >



C# static keyword





The main feature of the static keyword is that when anything is marked with a static keyword in a class, it belongs to the class and not to the object of the class.




The static keyword is used to create :







A static variable/static method of a class can be accessed -



//C# The value of a static variable is same and shared by all objects of its class.


using System;

class A
{

//A static variable of class A
static int value = 10;	            

//An instance method
public void SetValue(int v)
{
	value = v;
}

//An instance method
public int GetValue()
{
	return value;
}

public static void Main(String[] ar)
{
	//Creating first object of class A
	A ob1 = new A();
	
	//Setting the value of static variable
	//by using the first object
	ob1.SetValue(20); 
		    
	//Creating second object of class A
	A ob2 = new A();
	
	//Setting the value of static variable 
	//by using the second object
	ob2.SetValue(30);		    

	//Accessing value of static variable
	//by using the first object
	Console.WriteLine(ob1.GetValue()); 

	//Accessing value of static variable
	//by using the second object
	Console.WriteLine(ob2.GetValue());
}
}


Output is :


30
30


Program Analysis






Please share this article -




< Prev
Next >
< C# This Keyword
C# Polymorphism >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement