DEV Community

Cover image for Static in C# - Part 1
Luke
Luke

Posted on • Originally published at linkedin.com

Static in C# - Part 1

What is static?

Based on Microsoft (father of C-Sharp), it is modifier to declare a static member, which belongs to the type itself rather than to a specific object. For example, class have structure following:

class Test(){
    public string Content;
}
Enter fullscreen mode Exit fullscreen mode

In main function, we have:

static void Main(string[] args){
    var t1 = new Test() { Content = "Test 1" };
    var t2 = new Test() { Content = "Test 2" };

    Console.WriteLine(t1.Content); //output: Test 1
    Console.WriteLine(t2.Content); // output: Test 2
}
Enter fullscreen mode Exit fullscreen mode

So we can see the output will difference with other instance. But if we use static in class, what happen?

class Test(){
    public static string Content;
}
Enter fullscreen mode Exit fullscreen mode

And update in main function:

static void Main(string[] args){
    var t = new Test() { };

    //error here because you can't access static property through by instance
    Console.WriteLine(t.Content); 

    Test.Content = 'Static Content'
    Console.WriteLine(Test.Content); //output: Static Content

    ChangeContent("Update content with function");
    Console.WriteLine(Test.Content); //output: Update content with function
}

static void ChangeContent(string content)
{
    Test.Content = content;
}
Enter fullscreen mode Exit fullscreen mode

Compare main before and after, we have table conclusion:

Non static Static
Create at New instance create Compiler time
Access by Instance Class
Value Follow the instance Follow the class
Life time Until the instance deallocate Until program end

P/s: With static keyword, the variable will be stored in heap memory, below is short description about stack & heap:

Stack Heap
Store - Primitive type
- Reference variable
- Function call
- Object
- Static type
Structure Last In First Out (LIFO) Dynamic
Performance access Faster Slower

Top comments (0)