C#. Static classes, methods, variables. Static constructors. Keyword static




Static classes, methods, variables. Static constructors. Keyword static


Contents


Search other websites:



1. What elements of the C# programming language can be declared static?

In the C# programming language, static can be:

  • classes;
  • methods;
  • variables.

To make a class (method, variable) static, you should put the keyword ‘static’ before its declaration.

 

2. The concept of a static class. What are the features of using static classes in C# programs? The ‘static’ keyword

From the view of C# syntax static class – a class that is declared with the keyword static. The general form of a static class declaration is:

static class ClassName
{
  // fields and mehtods of class
  // ...
}

where ClassName – the name of static class.

 

3. Properties of static class

The implementation of the code of a static class is no different from the code of normal class except for two basic properties. In comparison with a non-static class, a static class has the following properties (differences):

  • you cannot create objects of a static class;
  • static class must contain only static members.

 

4. Examples that demonstrate the properties of a static class

Example 1. Let the static class MyStaticClass be given. In this class, one static member is declared with the name d.

// static class
static class MyStaticClass
{
  public static int d = 0;
}

If you try to create a static class object

// attempt to create a static class object
MyStaticClass ms; // error - you cannot create a static class object

this will cause a compilation error with the message:

Cannot declare a variable of static type 

Example 2. This example demonstrates the rule that a static class must contain only static members. Let the static class MyStaticClass be given. If in the static class MyStaticClass try to declare a non-static member d of integer type

// static class
static class MyStaticClass
{
  // nonstatic member without 'static' keyword
  public int d = 0; // error - you cannot declare a non-static instance in a static class
}

then at compile time the compiler will give the following error:

Cannot declare instance members in a static class

 

5. Examples of static classes

 Example 1. This example demonstrates the use of a static variable in a static class. A static class called Count is declared, in which one static variable ‘count’ is declared. This static variable is a counter that is shared in the non-static methods Add1(), Add2() of another class Methods.

The code for the classes Count and Methods is as follows:

// static class Count
static class Count
{
  // static variable count in class Count - shared resource
  public static int count;
}

// non-static class
class Methods
{
  // non-static class methods have access
  // to the static variable count of the static class Count
  public void Add1() // non-static method
  {
    // changing the value of a static variable
    Count.count++;
  }

  public static void Add2() // static method
  {
    Count.count = Count.count + 2;
  }
}

The following code shows calls to the count variaable of class Count and changing the value of this variable from the Add1(), Add2() methods.

Methods M = new Methods(); // create an object of class Methods

// check static member values
int n = Count.count; // n = 0

// call the non-static Add1() method of the Methods class
M.Add1(); // Increase Count.count by 1
n = Count.count; // n = 1

As can be seen from the example, the static data member Count.count is common to the Add1(), Add2() methods of the Methods class. If other classes with some methods were implemented in the program, this data element could be accessed from these methods.

If in this example the class Count is declared as non-static (without the keyword static)

// class Count - non-static
class Count
{
  // static variable count in class Count - shared resource
  public static int count;
}
...

then the result of the program will not change. The static variable Count.count can be used as a shared resource.

Example 2. The example demonstrates the use of a static method in a non-static class. The static method is a shared resource that does some common work.

The example declares the static AbsComplex() method, which finds the module of a complex number. The method is declared in the ComplexLibrary class. It also declares 2 classes that contain methods that use the AbsComplex() method in their calculations.

// non-static class containing a static method
class ComplexLibrary
{
  // static method, calculates the modulus of a complex number
  // it gets the value of the real (a) and imaginary (b) part of the complex number
  public static double AbsComplex(double a, double b)
  {
    return Math.Sqrt(a * a + b * b);
  }
}

// a class that contains a non-static method using the AbsComplex static method
class CalcComplex1
{
  // non-static method
  // It determines whether the modules of complex numbers are equals
  // this method uses the static method ComplexLibrary.AbsComplex() to calculate
  public bool EqualComplex(double a1, double b1, double a2, double b2)
  {
    double value1, value2;

    // using the static AbsComplex() method
    value1 = ComplexLibrary.AbsComplex(a1, b1);
    value2 = ComplexLibrary.AbsComplex(a2, b2);

    return value1 == value2;
  }
}

// another class that uses the AbsComplex() method from the ComplexLibrary class
class CalcComplex2
{
  // a method that determines whether the length of a complex number is equal to 0
  public bool ZeroComplex(double a, double b)
  {
    double value = ComplexLibrary.AbsComplex(a, b);
    return value == 0.0;
  }
}

The use of class methods CalcComplex1, CalcComplex2 can be as follows:

CalcComplex1 c1 = new CalcComplex1(); // create the instance of class
CalcComplex2 c2 = new CalcComplex2();
bool f;

f = c1.EqualComplex(3, 4, 2, 5); // f = False
f = c1.EqualComplex(1, 2, 2, 1); // f = True
f = c1.EqualComplex(-1, 2, -2, 1); // f = True
f = c2.ZeroComplex(0, 0); // f = True
f = c2.ZeroComplex(1, -5); // f = False

 

6. What are the advantages of using static classes, methods and variables in C# programs?

 Static classes, methods and variables are effective in the following cases:

  • if you need to create so-called extension methods. Extension methods are used to extend class functions. These methods are static;
  • if the program has some shared resource to which methods of different classes can have a call that processes the given resource (read or change its value). This share resource is declared as a static variable. For example, such a resource can be a certain call counter, a method that implements a unique processing, a unique file variable (resource), etc.;
  • static classes are effective when you need to combine with each other groups of static methods;
  • if you need to use shared hidden class data and organize access to this data from static and non-static methods.


 

7. What is the difference between calling a static method and a non-static method?

In any non-static class, both static and non-static methods can be declared. The difference between calling a static and non-static class method is as follows:

  • to call a non-static class method, you need to create an instance (object) of this class. A static method is called without creating a class object — the name of the class in which this static method is declared is specified before the method name.

For example. A non-static class Sqr is defined, containing the following two methods that return the square of an integer value:

  • GetSqr() – non-static method;
  • GetSqrStatic() – static method. 
// non-static class that contains non-static and static methods
class Sqr
{
  // non-static methods
  public int GetSqr(int x)
  {
    return x * x;
  }

  // static method
  public static int GetSqrStatic(int x)
  {
    return x * x;
  }
}

The following illustrates the use of these methods:

// Demonstration of calling static and non-static class methods
int t;

// 1. Calling the non-static method of class Sqr
// Need to create a class object
Sqr sc = new Sqr();
t = sc.GetSqr(7); // t = 49

// 2. Invoke of static method of class Sqr
t = Sqr.GetSqrStatic(7); // t = 49

As can be seen from the above code, to call a static method of a certain class, you must specify the name of this class before its name.

 

8. Is it possible to declare a hidden (private) static member in some class?

Yes, it is. In this case, this static member of the class will be available only within the boundaries of this class, that is, from the methods of this class. Access from other class methods will be impossible.

 

9. Is it possible to declare a static member of a class with a protected access modifier?

Yes, it is. In this case, access to the static member of the class will have class methods that are inherited from this class.

For example. Class A is declared, containing one static member a, which is declared as protected. A class B is also given, which inherits (extends) class A. From the SomeMethod() method of class B, is provided the access to protected-variable of class A.

// non-static class that contains non-static and static methods
class A
{
  protected static int a;
}

// class B inherits (extends) class A
class B : A
{
  void SomeMethod()
  {
    a = 10; // access to protected-variable of class A
  }
}

 

10. Can a non-static class contain static variables and static methods?

Yes. Examples of use in static methods in nonstatic class shown in paragraphs 5 and 7.

 

11. Is it possible to combine static and non-static methods in one class?

Yes, it is. But only in a non-static class. If a class is declared as static, then all methods and class variables must also be static (see paragraph 4 – Example 2).

For example. The example demonstrates the combination of static and non-static class methods to access the private static variable t in the class. A non-static class CMyClass is declared, containing a static variable, static and non-static methods for accessing it.

// non-static class
class CMyClass
{
  // private static variable
  private static int t;

  // static method that changes the value of a static variable t
  public static void Set(int _t)
  {
    t = _t;
  }

  // non-static method that reads the value of a static variable t
  public int Get() { return t; }
}

The following code demonstrates access to the hidden static variable t of class CMyClass

// demonstration of the combination of static and non-static class members
int x;

// 1. Access to a private static variable via the static Set() method
CMyClass.Set(777); // static variable t = 777

// 2. Read the value of a hidden static variable t
// 2.1. Create an object of class
CMyClass mc = new CMyClass();

// 2.2. Call a non-static Get() method through an instance of the class.
x = mc.Get(); // x = 777 - current value of static variable

This example well demonstrates how to organize work with the shared, hidden data of a class.

 

12. Is it possible to create an object of a non-static class in a static method of a static class?

Yes, it is. A classic example of this is the Main() function for console applications. This function is declared as static. However, you can create instances of any non-static classes in this function.

 

13. What are static constructors? Example

Static constructors allow to initialize static class variables.

Example. Declaration of a static constructor in the class is implemented.

// class that contains a static constructor
class CCount
{
  private static int count;

  static CCount()
  {
    count = 7; // initialization of static variable count
  }

  // access to internal static variable 'count'
  public static int Get()
  {
    return count;
  }
}

Demonstration of the work of the class CCount in some method

int x;
x = CCount.Get(); // x = 7

 

14. What are the rules (features) of using static constructors?

When using static constructors, pay attention to the following rules:

  • keyword static must be specified before static constructor;
  • in the class can be only one static constructor. This means that the static constructor cannot be overloaded;
  • static constructors are called when an instance of a class is created or when a static member of this class is accessed;
  • the static constructor in the program is executed only once. Even if you create multiple instances of the class containing the static constructor, still this static constructor will execute only once;
  • static constructors cannot have access modifiers (public, private);
  • if the class has a static constructor and a constructor creating an instance (or several constructors), then the static constructor is called first;
  • static constructor can not have parameters. If you try to create a parameterized static constructor in a class, a compilation error will occur.

 

15. Is it possible to initialize non-static class variables from static constructors?

No, it isn’t. From static constructors, you can initialize only static variables of the same class. If non-static variables are also declared in this class, then there is no access to them from static constructors.

For example.

class CFileName
{
  private static string fname; // hidden static variable
  private string folder; // hidden non-static variable

  // static constructor
  static CFileName(string _fname)
  {
    fname = _fname; // access to static class variables only
    // folder = ""; // error, folder - non-static variable
  }
}

 


Related topics