Sunday, January 6, 2013

What is difference between Static, read only and Static read only variable in C#.???????


Static: 

Static Variables, Methods or Classes are directly accessible without creating instance of a class as: 


public class NonStaticClass 
{ 
//Static method 
public static string HelloWorld(string Name) 
{ 
return "Hello" + Name; 
} 

//Static variable 
public static string staticname 
{ 
get; 
set; 
} 
} 

Accessing above method and variable 

protected void Page_Load(object sender, EventArgs e) 
{ 
//Calling static method 
lblNonStatic.Text = NonStaticClass.HelloWorld("sunder"); 

//Calling static variable 
string name = NonStaticClass.StaticVariable; 
}

ReadOnly: 
In such cases where we want to pre-set the value of the variable which should not be changed by any method further we user ReadOnly for instance: 

public class ManageTime 
{ 
//ReadOnly variable 
readonly DateTime StartTime; 

public ManageTime() 
{ 
this.StartTime = DateTime.Now; 
} 

//Method Accessing StartTime 
public DateTime GetStartTime() 
{ 
//You may want to change the time here. But, it is not allowed due to "ReadOnly" nature of property 
return this.StartTime; 
} 
} 

Static ReadOnly: 

As we seen above static class does not need instantiation so in the same way static readonly variables are pre-populated and stored in the memory. 

Static ReadOnly variable can not be assigned on Initialization because of its static nature. 


public class StaticManageTime 
{ 
//ReadOnly variable 
static readonly DateTime StartTime=DateTime.Now; 

public StaticManageTime() 
{ 
If you will try to assign the value of StartTime in constructor. It will throw an error. 

this.StartTime = DateTime.Now; 

//<- error "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) 
} 

//Method Accessing StartTime 
public DateTime GetStartTime() 
{ 
//You may want to change the time here. But, it is not allowed due to "ReadOnly" nature of property 
return StartTime; 
} 
} 

No comments:

Post a Comment

Creating mirror of BST