developmentor - a developer services company				  
				      C# Tutorial
   Modules

Static


Goals:

  • Code a class with static fields and methods.
  • Practice with variable initializers for static fields.
  • Write a static constructor.

Overview

Intuitively, static fields have much in common with the "global variables" used by other languages: the key idea is that there is one copy of each static field that is shared by all clients.

C# offers three options for initializing static fields and provides well defined rules for the execution order of the various options. The first initialization option is to simply accept their default values. The default value depends on the type: numeric types get set to zero, Booleans to false, characters to the null character, and references to null. The second initialization option is to assign an initial value at the point of definition. The third initialization option is the use of a static constructor. All the static initialization code is run only once since their is only one copy of the static data.

Methods can be static. Code inside a static method can only access the static parts of the class, instance fields and methods are not available.

Both static fields and methods must be accessed only through the classname, never through an instance. This rule is sensible because the statics are associated with the class as a whole and not with a particular instance.


part 1- Static field

Here we will use a static field to generate id numbers for a student class. The field will be static since we want all students to draw from the same source of id numbers; that is, we want a shared resource.

steps:

  1. Consider the following Student class. There are currently two fields: name and age. The constructor takes the user data and assigns it to the fields. There is no additional code required for this part of the exercise.

    class Student
    {
    	string name;
    	int    age;
    
    	public Student(string name, int age)
    	{
    		this.name = name;
    		this.age  = age;
    	}
    }
    

  2. Each student needs an id number to uniquely identify them at their university. Add an integer field to the student class to represent the id number.

  3. The student id number will be generated inside the student class using a static field to store the next value to be assigned. A static field is appropriate since we want all students to get their id number from the same source in order to guarantee a unique id number for each student. Add a static nextId field to the Student class. Use a static constructor or inline initialization to set the initial value to 1. Modify the constructor to assign from nextId to the id field. Be sure to increment the nextId field after using its current value.

  4. Add a driver class with a Main method. Create a few Student objects to test your implementation.

Solutions:


part 2- Static methods

Static methods are often used for small "utility" operations that take in some data through parameters, perform a calculation, and return the result. These methods do not need a this object associated with the call since they get all the information they need through their parameters. Making the methods static also has the advantage that they are easier for clients to use since they are invoked simply using the class name rather than through an instance of the class.

steps:

  1. Create a class called MathUtils. Add two public static methods Min and Max. The methods should take two int parameters, perform their operation, and return the result.

  2. Create a driver class with a Main method. Call the Min and Max methods to test your work.

Solutions:


part 3- Random number generator (optional)

Here we create a class that supplies a convenient random number generator. The class will make use of a static field and a static method. It will also give practice with the options for initializing a static field: static variable initializer and static constructor.

The .NET Framework class library provides a class named System.Random that we will use to implement our random number generator. The Random class will do most of the work for us; however, Random requires users to instantiate an object of the Random class and call instance methods to generate random numbers. This type of interface makes it easy for the Framework library designer since the Random object needs to store state information. Forcing users to instantiate the class ensures that memory is allocated for the use of the generator.

This interface is not ideal for users who would like one generator that can easily be shared by their entire application. To support this model of programming we will create a class that wraps a Random object with a static method interface.

steps:

  1. Complete the implementation of the following RandomNumberGenerator class. The generator exposes just one method Next which returns a random number between 0 and bound-1. You will need to add a static field of type System.Random. Use a variable initializer to create a Random object and assign it to your field. The default constructor for the Random class uses the current time to create a seed. This will give a different sequence of values each time the program is run so it is a good choice for our use.

    class RandomNumberGenerator
    {
    	public static int Next(int bound)
    	{
    		...
    	}
    	...
    }
    

  2. Using a static variable initializer to allocate the Random object is less than ideal because the entire initializer must fit in one line of code and the required expression is relatively complicated. Modify the implementation of the random number generator to use a static constructor to perform the initialization. Use of a static constructor will allow the initialization code to be spread across several lines which should make it more readable.

    public class RandomNumberGenerator
    {
    	static RandomNumberGenerator()
    	{
    		...
    	}
    	...
    }
    

  3. Add a Driver class with a Main method to test your work.

Solutions:

This material is excerpted from the Programming C# course offered by DevelopMentor.