Search code examples
c#oopstaticprivatepublic

Confused about public, static and private methods/classes/variables in C#


I'm a beginner in programming with C# and coming from a Python background.

I'm confused about the keywords public and static. Can someone please clarify the difference for me?

(Btw, I already know that Private variables/methods can never be accessed outside the function, whereas Public can be)

Here is just something I randomly tried to understand the difference between static, and non-static methods.

using System;

public class MainClass
{
    public static void Main ()
    {
        int[] anArray =  getAnArray();

        foreach (int x in anArray) 
        {
            Console.WriteLine (x);
        }

        MainClass m = new MainClass ();
        foreach (int x in anArray) 
        {
            m.Print(x);
        }
    }

    public static int[] getAnArray() 
    {
        int[] myArray = { 1, 2, 3, 4 };
        return myArray;
    }

    public void Print(int x) 
    {
        Console.WriteLine(x);
    }
}

I understand that to use the non-static method Print, I first need to create an instance of the MainClass, then access the method by doing m.Print()

However I don't understand when exactly to use which. As far as I can see it would be a lot easier if Print was static, as I wouldn't need to create a new instance of my own function.

For eg, this would be simpler

private static void Print(int x)
{
    Console.WriteLine (x);
}

And call the Print function with Print(x) instead of creating the instance of Main first.

So basically when to use what? When to use static or non-static in regard to not only methods but variables and even classes? (For eg when should I use public static class MainClass)


Solution

  • static members are class members, and shared between all instances of that class.

    public methods/properties are available to other classes. It's possible to have a public static member which is available to other classes.

    You can't access a non-static member from a static member.

    If a function doesn't need access to any instance variables then it can be made static for a slight performance gain, but there are more useful ways to use static members.

    Some uses for static off the top of my head:

    • Singletons (you create a protected constructor that is accessed by a static variable inside the class)
    • Console.WriteLine is static
    • Locks/semaphores (where there is only one available at the class level that is shared by all instances)

    If something makes sense to be shared by all instances of a class, make it static