Static And Instance Members In C#

In our previous post we learned about constructors in csharp but while discussing about types of constructors we were introduced to Static Constructors. You may have seen static written in our code or text earlier but might not be aware about this static thing. This post is about static keyword in csharp and we will learn differences between static & non static members.


What are static and instance members in csharp





Static Keyword In C#


Static in terms of programming means something which will stay in memory from the beginning and will not be associated with the instance but with the type. In easy words if we specify something as static in csharp then it is accessible throughout the runtime of application without creating any instance of its respective class. If we need to declare something static then we need to write static just before its type, see below examples to understand how to define something as static in c#


//Static Class
public static class XYZ{
    //Fields and Methods
}

//Static Field
public static int xyz;

//Static Property
public static int XYZ {get; set;}

This is how we declare classes or fields as static. Also for static classes, there's a thumb rule : If we declare a class as static then all the members of that class must be declared as static. If we don't obey this rule the compiler will throw up an error saying cannot declare instance members in static class.
If there's a class and some of its fields are static and some are not, then those fields or property which are static are called Static Members of that class and rest of those which are declared without static keyword are called Instance Members. Let's see the difference between these two members of class.


Difference Between Static Members And Instance Members


As we know that all the the fields, properties and methods of a class are called its members. And if any of those member has static keyword written before its type then it becomes static member otherwise its an instance member. Lets see below example to understand the difference between these members in detail.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CheezyCodeApp
{
    public static class StaticClass
    {
        public static int staticField = 10;

        //Error: Cannot declare instance member in static class
        //public int nonstaticField = 10;

    }

    public class NonStaticClass
    {
        public int nonstaticField = 20;
        public static int staticField = 30;
    }

    class CheezyCode
    {
        static void Main()
        {
            //Error: Cannot create instance of static class
            //StaticClass staticClass = new StaticClass();
            
            Console.WriteLine(StaticClass.staticField); //10

            //Error: An object reference is required for 
            //the non-static field, method, or property
            //Console.WriteLine(NonStaticClass.nonstaticField);

            Console.WriteLine(NonStaticClass.staticField); //30

            NonStaticClass nonStaticClass = new NonStaticClass();
            Console.WriteLine(nonStaticClass.nonstaticField); //20

            //Error: Member 'CheezyCodeApp.NonStaticClass.staticField' cannot be accessed 
            //with an instance reference; qualify it with a type name instead
            //Console.WriteLine(nonStaticClass.staticField);
        }
    }
}

In the above example, we have created two classes : one is static and another is non-static. Now let's see interesting findings about static, refer above code snippet for below points


  • StaticClass can only have static members. Even if we try to include a non-static member, then compiler shows up an error : Cannot declare instance member in static class. By instance member we and everyone else means Non-Static Member of a class.
  • NonStaticClass has static as well as instance members, which is fine. But ways to access these members are different.
  • We cannot create instance of StaticClass. Its members are directly accessible.
  • To access static members, we just need to append classname before member name like StaticClass.staticField.
  • To access instance members (Non-Static Members) creation of instance is must. Even the name(Instance members) suggests that. I hope you know instance of class is created by using new ClassName();
  • If you try to access static member from an instance object, then compiler comes into picture and throw up a crisp & helpful error : Static field of NonStaticClass cannot be accessed with an instance reference; qualify it with a type name instead. Which means that only way static members can be accessed, is by appending classname before the member name.
  • Concept wise remember, that instance members are created in memory every time a new instance is created and their value is different across different instances. But in case of static members, they are created only once when the application starts and they return same value at all times.

Learn from our video tutorial on Static:




So that's all about Instance members & Static Members in C#. Paste above code in your console application and try out different possibilities, you might find something new with it.
Let us know if you have any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)



Comments

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example