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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With