Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding static in C#

Tags:

c#

I'm learning C# and I'm having trouble understanding the static keyword.

Say I have the following code:

using System;
using System.IO;
using System.IO.Ports;

class PortThing
{
    SerialPort port;

    void InitPort()
    {
        if(!File.Exists("/dev/whatever"))
        {
            System.Console.WriteLine("Device not found.");    
            port = null;  
        }
        //else port = something
    }

    public static void Main(string[] args)
    {
        InitPort();
        System.Console.WriteLine("Done.");
    }
}

As far as I can understand, a static method is one that belongs to the class rather than to the object of that class. So static methods can't reference nonstatic methods/fields since they require instantiating a class.

Compiler complains about Main() calling InitPort() and wants to make it static. I could do so but that would require to make port a static field. Following this line of thought, everything would end up being static.

What am I getting wrong?

like image 462
Igor Avatar asked Dec 05 '22 00:12

Igor


1 Answers

You are getting it right. Static methods can access only static members. Non-static members need an instance of the class in order to access them. So you could do this:

public static void Main(string[] args)
{
    new PortThing().InitPort();
    System.Console.WriteLine("Done.");
}

This way you are calling the instance method InitPort on a given class instance and you can keep the port field non-static.

like image 122
Darin Dimitrov Avatar answered Dec 07 '22 14:12

Darin Dimitrov