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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay