Static Fields

Introduction

If you have a class, to access it outside its body, you can declare a variable of it as we have done so far. In the same way, you can declare various instances of the same class.

public class Chemistry
{
    public string Element;
    public string Symbol;
    public int AtomicNumber;
    public decimal AtomicWeight;
}

public class Exercise
{
    public void Create()
    {
        Chemistry elm = new Chemistry()
        {
            Symbol = "Be",
            AtomicNumber = 4,
            Element = "Beryllium",
            AtomicWeight = 9.0121831M
        };

        Chemistry chem = new Chemistry()
        {
            Symbol = "B",
            AtomicNumber = 5,
            Element = "Boron",
            AtomicWeight = 10.81M
        };
    }
}

A variable you have declared of a class is also called an instance of the class. Each instance gives you access to the members of the class but each instance holds the particular values of the members of its instance. All of the fields or methods of the classes we have used so far are referred to as instance members because, in order to access them, you must have an instance of a class declared in another class in which you want to access them.

In your application, you can declare a variable and refer to it regardless of which instance of an object you are using. Such a variable is referred to as static.

A Static Field

To declare a field of a class as static, that is, to create a static field, type the static keyword on its left. Here is an example:

public class Chemistry
{
    static string Category;  
}

In the same way, you can create as many static fields as you want. As we saw in previous lessons, you can control access to a field using a modifier (private, public, or internal). If you apply the modifier, the static keyword can be written before or after it, as long as it appears before the data type. Here are examples:

public class Chemistry
{
    public static int Period;
    static public int Group;
}

To access a static variable, you must "qualify" it where you want to use it. Qualifying a member means you must specify its class, followed by a period, and followed by the static field.

Notice that, when a field has been created as static, you don't need an instance of the class to access that member variable outside of the class. Based on this, if you declare all members of a class as static, you don't need to declare a variable of their class in order to access them.

In your class, you can create a combination of static and non-static fields if you judge it necessary. You just have to remember that, to access a static variable, you don't create an instance of the class. To access a non-static variable, you must declare a variable for the class.

You can create a method in a class. That method can directly access static and non-static members by their names. From a local method, a static field can be accessed either by its name or by qualifying it. Here are examples:

public class Element
{
    public string Symbol;
    public string ElementName;
    public int AtomicNumber;
    public decimal AtomicWeight;

    public static string Category;

    private void Initialize()
    {
        Symbol = "Be";
        ElementName = "Beryllium";

        Category = "Alkali Earth Metal";
    }
}

Static Methods

Introduction

Like a field, a method of a class can be made static. Such a method can access any member of the class but it depends on how the member was declared. Remember that you can have static or non-static members of a class.

Creating a Static Method

To define a method as static, type the static keyword to its left. Here is an example:

public class Element
{
    static void Display()
    {
    }
}

A static method can also use an access modifier. You can write the access modifier before or after the static keyword. Here is an example:

public class Chemistry
{
    public static void Display()
    {
    }
}

As mentioned for a static field, using a static method depends on where it is being accessed. To access a static member from a static method of the same class, you can just use the name of the static member. Here is an example:

public class Element
{
    static private string Category;

    private static void Categorize()
    {
        Category = "Alkali Metal";
    }
}

You can also qualify the member by typing the name of the class, followed by a period, followed by the member. Here is an example:

public class Element
{
    static private string Category;

    private static void Categorize()
    {
        Chemistry.Category = "Alkali Metal";
    }
}

To access a non-static member from a static method of the same class, you must declare a variable of the class and use it. Here are examples:

public class Element
{
    public string Symbol;
    public string ElementName;
    public int AtomicNumber;
    public decimal AtomicWeight;

    public static void Display()
    {
        Element elm = new Element();

        elm.AtomicNumber = 12;
    }
}

Static Classes

Introduction

Like a variable or a method, a class can be made static. A static class is a class whose members must be:

Creating a Static Class

To create a static class, precede the class keyword with the static keyword. Based on the above two rules, all members of a static class must be made static, and all members are accessed without an instance of the class. Here is an example:

public static class Region
{
    public static string Name;
    public static string States;
}

public class Statistics
{
    private Form frmStatistics;
    private TextBox txtName;
    private TextBox txtStates;

    public void Create()
    {
        Region.Name = "New England";
        Region.States = "Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, and Vermont";
    }
}

The two rules we reviewed for static classes are mostly for languages other than C# (most other languages, including those that support the .NET Framework (Visual Basic, F#, C++/CLI, etc), don't have the true concept of static classes; they only apply its features). As we saw in the previous section, in C#, a static class is created with the static keyword. From there, the two rules must be applied to all members of the class.

Static Constructors

Like a normal method, a constructor can be made static. There are rules you must follow. If you want to use a static constructor, you must explicitly create it (the compiler doesn't create a static constructor for you).

The static constructor must become the default constructor. That is, you must create a constructor that doesn't use any parameter. Here is an example:

public class Person
{
    public string firstName;

    static Person()
    {
    }
}

If you create a static constructor, you cannot directly access the non-static fields of the class. You can still access any field of the class as you see fit. Here are examples:

public class Person
{
    public string firstName;

    static Person()
    {
    }
}

public class Exercise
{
    private void Create()
    {
        Person pers = new Person();

        pers.firstName = "Gertrude";
    }
}

To use a static constructor, you have various options. To initialize a field in the static constructor, you can declare a variable for the class and access the firld. Here is an example:

public class Person
{
    public string firstName;

    static Person()
    {
        Person pers = new Person();

        pers.firstName = "Gertrude";
    }
}

In reality, one of the reasons for using a static constructor is to initialize the static fields of the class or perform any action that would be shared by all instances of the class. Therefore, another option to use a static constructor is to initialize the static fields. After doing this, when accessing the initialized static field(s), it(they) would hold the value(s) you gave it(them). Here is an example:

public class Person
{
    public static string firstName;

    static Person()
    {
        firstName = "Gertrude";
    }
}

public class Exercise
{
    private void Create()
    {
        Person.firstName;
    }
}

Because the constructor is static, you cannot access it by declaring a variable for the class.

Another rule to observe with a static constructor is that you must not add an access modifier to it. The following will result in an error:

public class Person
{
    public static Person()
    {
    }
}

You can create a class that uses a combination of a static constructor and one or more other (non-static) constructors. Here is an example:

public class Person
{
    static Person()
    {
    }

    public Person(string first, string last)
    {
    }
}

If you create such a class and if you want to declare a variable for it, the default constructor doesn't exist or is not available. If you want to declare a variable, you must use a constructor that uses a parameter. Here is an example:

using System;

public class Person
{
    public string firstName;
    public string lastName;

    static Person()
    {
    }

    public Person(string first, string last)
    {
        firstName = first;
        lastName = last;
    }
}

public class Exercise
{
    public void Create()
    {
        Person pers = new Person("Gertrude", "Monay");
    }
}

this Object

Introduction

If a class contains fields and methods, the (non-static) fields are automatically available to all method(s) of the class, even fields that are private. When working inside a class, such as accessing a field or a method of the class from another member of the same class, to let you indicate that you are referring to the class or to a member of the same class, the C# language provides a special object named this.

Accessing a Member of this Class

While working from within a class, to access one of its non-static members, you can type this followed by a period and the desired member. Here are examples:

public class Circle
{
    private decimal radius;

    public readonly decimal PI = 3.14159m;

    public decimal CalculateDiameter()
    {
        return this.radius * 2;
    }

    public decimal CalculateCircumference()
    {
        return this.CalculateDiameter() * this.PI;
    }

    public decimal CalculateArea()
    {
        return this.radius * this.radius * this.PI;
    }
}

Because the this keyword indicates that you are using a member from within the class, a method can use a parameter that has the same name as a member of the class and, by using the this keyword, you would not have any name conflict. Here is an example:

class Circle
{
    private decimal radius;

    public readonly decimal PI = 3.14159m;

    public Circle(decimal radius)
    {
        // In "this.radius", the radius is the one in the class
        // In "radius", the radius is the parameter of the method
        this.radius = radius;
    }
}

As you might have realized from the above code and from previous lessons, the this keyword is mostly optional. Other than that, the public members can still be accessed outside the class.

When using this, you can access any member of a class within any method of the same class. There are rules you must observe when using this:

A Field with a Type and Name as the Same

In the previous lesson, we saw that a field can use the same name for its type and its name. Here is an example we saw:

public class Employee
{

}

public class TimeSheet
{
   	private decimal timeWorked;
    private string filingStatus;

    public Employee Employee;
}

If you want to indicate when you are accessing the field, you should use the this object, but this is not a requirement. This can be done as follows:

public class Employee
{

}

public class TimeSheet
{
    public Employee Employee;

    public TimeSheet(Employee staff)
    {
        this.Employee = staff;
    }
}

this Method Returns an Object of its Class

As we saw in the previous lesson, a method of a class can be made to return an object of its own class. An alternative is to return the this object. Here is an example:

public class Chemistry
{
    public string Element;
    public string Symbol;
    public int AtomicNumber;
    public decimal AtomicWeight;

    public Chemistry Initialize()
    {
        Symbol = "N";
        AtomicNumber = 7;
        Element = "Nitrogen";
        AtomicWeight = 14.007M;

        return this;
    }
}

The Static Features of a Class

Accessing Static and Non-Static Members

We have seen that, to access a non-static member from a static member of the same class, you can simply use the namae of the member. On the other hand, to access a non-static member from any static method, including methods outside the class of the non-static member, you must declare a variable of the class and access the member through that instance. You have two options.

Directly Using the Static Members of a Class

The usual way to call a static method is to qualify it from the name of its class. As an alternative, in the top section of the document where you want to call a static method, type using static followed by the name of the class and a semicolon. In the document where you need the method, just call it by its name.

Class Nesting

A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, click inside an existing class and type the necessary code for the new class, starting with the class keyword followed by a name and {}. If you are using Microsoft Visual Studio, select the whole class. Right-click the selection and click Surround With... In the list, double-click class

Here is an example of a class called Inside that is nested in a class called Outside:

public class Outside
{
    public class Inside
    {
    }
}

In the same way, you can nest as many classes as you wish in another class and you can nest as many classes as you want inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can create all necessary fields and/or methods in the nested class or in the nesting class.

When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately.

The name of a nested class is not "visible" outside of the nesting class. To access a nested class outside of the nesting class, you must qualify the name of the nested class anywhere you want to use it. For example, if you want to declare an Inside variable somewhere in the website but outside of Outside, you must qualify its name. Here is an example:

public class Outside
{
    public class Inside
    {
        public Inside()
        {
        }
    }

    public Outside()
    {
    }
}

public class Exercise
{
    public void Create()
    {
        Outside recto = new Outside();
        Outside.Inside ins = new Outside.Inside();
    }
}

Because there is no programmatically privileged relationship between a nested class and its "container" class, if you want to access the nested class in the nesting class, you can use its static members. In other words, if you want, you can create static members (fields and/or methods) of the nested class you want to access in the nesting class. Here is an example:

public class Outside
{
    public class Inside
    {
        public static string InMessage;

        public Inside()
        {
        }

        public static void Show()
        {
        }
    }

    public Outside()
    {
    }

    public void Display()
    {
        System.Console.WriteLine(Inside.InMessage);
        Inside.Show();
    }
}

class Exercise
{
    public void Create()
    {
        Outside recto = new Outside();
        Outside.Inside ins = new Outside.Inside();

        Recto.Display();
    }
}

Previous Copyright © 2001-2019, FunctionX Next