Friday, July 06, 2007

Static in C#.net

The static keyword is used to have static data members and function members in the C# code .There can be a situation when we require to have a field in the class which is used to store some global value .Which doesn’t change and can be used as global variable .
We can also have a static constructors where we can initiate the value for the static data members used in the class.
We also make use of static methods in C# .The conditions when using a static method is that it should not use the instance variable or any instance methods in it .

Code samples :

class StaticExamples
{
public static string name; // Static field
public static uint age; // Static field
public static uint retirementAge; // Static field
public int salary; // Non Static field
public int tax; // Non Static field
static StaticExamples() // Static constructor
{
name = "naroor";
age = 25;
retirementAge = 58;

}
// Static method
public static uint GetRemainingYears(uint age,uint retirementAge)
{
return retirementAge - age;
}
}

Usage ::

MessageBox.Show("First static field ::" + StaticExamples.age.ToString());
MessageBox.Show("Second static field ::" + StaticExamples.name);
StaticExamples StaticObj = new StaticExamples();
StaticObj.salary = 20000;
StaticObj.tax = 5000;
MessageBox.Show("First Non static field :: " + StaticObj.salary.ToString());
MessageBox.Show("Second Non static field :: " + StaticObj.tax.ToString());

uint age;
age = StaticExamples.GetRemainingYears(StaticExamples.age, StaticExamples.retirementAge);
MessageBox.Show("The retirement age for " + StaticExamples.name + " is " + age.ToString());

So you can find that for calling static field and static methods we don’t have to instantiate a method of the class.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home