Static Class Attributes

Lesson 29
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

Static class attributes are attributes that belong to a class itself, rather than to individual objects created from the class. They are also sometimes referred to as class-level attributes or static variables.

In C#, you can define a static class attribute using the static keyword. Here’s an example:

class MyClass
{
    public static int count = 0;
    public string name;

    public MyClass(string name)
    {
        this.name = name;
        count++;
    }
}
In this example, we have a class called `MyClass` that has a static integer attribute called count. We also have a constructor method that takes a string argument called name, sets the instance variable name to the argument value, and increments the static count attribute by 1.

The count attribute belongs to the MyClass class itself, rather than to any individual object created from the class. This means that if we create multiple objects of `MyClass`, they will all share the same count attribute.

Here's an example of how we could use the `count` attribute:

```csharp
MyClass obj1 = new MyClass("object 1");
MyClass obj2 = new MyClass("object 2");
MyClass obj3 = new MyClass("object 3");

Console.WriteLine("Number of objects created: " + MyClass.count); // Output: Number of objects created: 3

In this example, we create three objects of MyClass, which each call the constructor method and increment the count attribute. We can then access the count attribute using the class name followed by the attribute name (e.g. MyClass.count) and output the number of objects created. The output will be “Number of objects created: 3”.