简体   繁体   中英

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)

Small, self-explaining example of public/non-static and static methods in use:

Car car1 = new Car();
car1.setBrand("Ford"); //public non-static method
Car car2 = new Car();
car2.setBrand("Opel"); //public non-static method

Car.CompareParameters(car1, car2); //static method

Basically, non-static methods and properties describe objects of such class.

You can't call Car.setBrand() - non-static method using class name.

As a general rule of thumb:

Static methods The static keyword makes the method directly accessible without having to create an instance of an object. As such, any state or side-effects it has will be static , ie "global". So only use static to create pure functions, ie methods that derive a return value from their inputs only, neither reading or writing state from outside the method.

The use of static is a trade-off between simplifying code and testing. The more side-effects you put in to a static method, the harder your code will be to test.

public methods Anything marked public is accessible throughout your application. Marking something internal restricts it to just that assembly (you can view the term "assembly" as equivalent to a project in your solution") and private restricts it to only being assessable within a class/struct.

If you follow the principle of encapsulation, then the rule to follow is use private all the time, only using internal if you need to. And only use public if you really have to.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM