Shiman’s Weblog

Collecting stones from the sea-shore.

Uses of the Static Keyword in C#.NET

In C#, classes, structures and their members may be defined using the static keyword. While doing so, the static member must be invoked directly from the class level, rather than from a type instance. To illustrate the distinction, consider a good friend of ours, the most commonly used System.Console. As you have seen, you do not have to invoke the WriteLine() method from the object level:

// Error! WriteLine() is not an instance level method!
Console c = new Console();
c.WriteLine("I can't be printed...");

but instead simply prefix the type name to the static WriteLine() member:

// Correct! WriteLine() is a static method.
Console.WriteLine("Thanks...");
  • Rule: Static members can operate only on static class members.

If you attempt to make use of nonstatic class members (also called instance data) within a static method, you receive a compiler error.The static keyword can be used before Data, Methods, Constructors and Classes. Lets take a look at them.

Static Data

a type may define static data. When a class defines nonstatic data, each object of this type maintains a private copy of the field. For example, assume a class that models a savings account:

// This class has a single piece of nonstatic data.
class SavingsAccount
{
public double currentBalance;
public SavingsAccount(double balance)
{ currentBalance = balance; }
}

When you create SavingsAccount objects, memory for the currentBalance field is allocated for each instance. Static data, on the other hand, is allocated once and shared among all object instances of the same type. To illustrate the usefulness of static data, add a piece of static data named interestRate to the SavingsAccount class:

class SavingsAccount
{
public double currentBalance;
public static double interestRate = 0.04;
public SavingsAccount(double balance)
{ currentBalance = balance; }
}

If you were to create three instances of SavingsAccount as so:

static void Main(string[] args)
{
// Each SavingsAccount object maintains a copy of the currBalance field.
SavingsAccount s1 = new SavingsAccount(50);
SavingsAccount s2 = new SavingsAccount(100);
SavingsAccount s3 = new SavingsAccount(10000.75);
}

the in-memory data allocation would look something like the figure.

Let’s update the SavingsAccount class to define two static methods to get and set the interest rate value. As stated, static methods can operate only on static data. However, a nonstatic method can make use of both static and nonstatic data. This should make sense, given that static data is available to all instances of the type. Given this, let’s also add two instance-level methods to interact with the interest rate variable:

class SavingsAccount
{
public double currentBalance;
public static double interestRate = 0.04;

public SavingsAccount(double balance)
{ currentBalance = balance; }

// Static methods to get/set interest rate.
public static void SetInterestRate(double newRate)
{ interestRate = newRate; }
public static double GetInterestRate()
{ return interestRate; }

// Instance method to get/set current interest rate.
public void SetInterestRateObj(double newRate)
{ interestRate = newRate; }

public double GetInterestRateObj()
{ return interestRate; }
}

Now, observe the following usage and the output.

static void Main(string[] args)
{
SavingsAccount s1 = new SavingsAccount(50);
SavingsAccount s2 = new SavingsAccount(100);
// Get and set interest rate.
Console.WriteLine("Interest Rate is: {0}", s1.GetInterestRateObj());
s2.SetInterestRateObj(0.08);
// Make new object, this does NOT 'reset' the interest rate.
SavingsAccount s3 = new SavingsAccount(10000.75);
Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate());
Console.ReadLine();
}

Static Methods

Let us consider a class named Teenager that defines a static method named Complain(), which returns a random string, obtained in part by calling a private helper function named GetRandomNumber():

class Teenager
{
private static Random r = new Random();

private static int GetRandomNumber(short upperLimit)
{
return r.Next(upperLimit);
}

public static string Complain()
{
string[] messages = new string[5]{ "Do I have to?", "He started it!",
"I'm too tired...", "I hate school!",
"You are sooo wrong."
};
return messages[GetRandomNumber(5)];
}
}

Notice that the System.Random member variable and the GetRandomNumber() helper function method have also been declared as static members of the Teenager class.

Like any static member, to call Complain(), prefix the name of the defining class:

// Call the static Complain method of the Teenager class.
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
Console.WriteLine("-> {0}", Teenager.Complain());
}

And like any nonstatic method, if the Complain() method was not marked static, you would
need to create an instance of the Teenager class before you could hear about the gripe of the day:

// Nonstatic data must be invoked at the object level.
Teenager joe = new Teenager();
joe.Complain();

Static Constructors

As you know, constructors are used to set the value of a type’s data at the time of construction. If you were to assign the value to a piece of static data within an instance-level constructor, you would be saddened to find that the value is reset each time you create a new object! For example, assume you have updated the SavingsAccount class as so:

class SavingsAccount
{
 public double currBalance;
 public static double interestRate;
 public SavingsAccount(double balance)
 {
 currBalance = balance;
 interestRate = 0.04;
 }
 //...
}

If you execute the previous Main() method, you will see a very different output. Specifically notice how the currInterestRate variable is reset each time you create a new SavingsAccount object.

While you are always free to establish the initial value of static data using the member initialization syntax, what if the value for your static data needed to be obtained from a database or external file? To perform such tasks requires a method scope to author the code statements. For this very reason, C# allows you to define a static constructor:

class SavingsAccount
{
 //...
 // Static constructor.
 static SavingsAccount()
 {
 Console.WriteLine("In static ctor!");
 currInterestRate = 0.04;
 }
}

Few points of interest regarding static constructors are:

  • A given class (or structure) may define only one single static constructor.
  • A static constructor is executed exactly one time, no matter of how many objects of the type are created.
  • A static constructor does not take an access modifier and cannot take any parameters.
  • The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
  • The static constructor executes before any instance-level constructors.

Given this modification, when you create new SavingsAccount objects, the value of the static data is preserved, and the output is identical to the output of the Static data program output.

Static Classes

When a class has been defined as static, it is not creatable using the new keyword, and it can contain only static members or fields (if this is not the case, you receive compiler errors). Static classes are sealed class by default that means a static class cannot be inherited by other class.

This might seem like a very useless feature, given that a class that cannot be created and cannot be inherited does not appear all that helpful. However, if you create a class that contains nothing but static members and/or constant data, the class has no need to be allocated in the first place. Consider the following type:

static class UtilityClass
{
 public static void PrintTime()
 { Console.WriteLine(DateTime.Now.ToShortTimeString()); }

 public static void PrintDate()
 { Console.WriteLine(DateTime.Today.ToShortDateString()); }
}

Given the static modifier, object users cannot create an instance of UtilityClass:

static void Main(string[] args)
{
    UtilityClass.PrintDate();
    // Compiler error! Can't create static classes.
    UtilityClass u = new UtilityClass();
    //...
}

May 27, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | 1 Comment

Deadlock

Boss said to secretary: For a week we will go abroad, so make arrangement.

Secretary make call to Husband: For a week my boss and I will be going abroad, you look after yourself.

Husband make call to secret lover: My wife is going abroad for a week, so lets spend the week together.

Secret lover make call to small boy whom she is giving private tuition: I have work for a week, so you need not come for class.

Small boy make call to his grandfather: Grandpa, for a week I don’t have class ‘coz my teacher is busy. Lets spend the week together.

Grandpa(the 1st boss ) make call to his secretary: This week I am spending my time with my grandson. We cannot attend that meeting.

Secretary make call to her husband: This week my boss has some work, we canceled our trip.

Husband make call to secret lover: We cannot spend this week together, my wife has canceled her trip.

Secret lover make call to small boy whom she is giving private tuition: This week we will have class as usual.

Small boy make call to his grandfather: Grandpa, my teacher said this week I have to attend class. Sorry I can’t give you company.

Grandpa make call to his secretary: Don’t worry this week we will attend that meeting, so make arrangement .

May 27, 2008 Posted by shiman | Computer Science, Jokes | , , | 4 Comments