Fields marked as 'static'

Hey! I'm going through a Udemy course on C# and something has stumped me and I can't work it out... The video is covering fields within classes, which I understand fine. However, in the video, they have a 'int myResult' variable which isn't marked as static. The variable is being used in various methods without the compiler complaining. However, when I've recreated it, my variable needs to be marked as static. Here's my code
namespace FieldsAndInstanceVariables
{
internal class Program
{
// As the variable is declared in the class and not a method, it's a 'field'
// This can be used throughout the class
static int myResult;

static void Main(string[] args)
{
myResult= Add(5, 5);
Console.WriteLine($"5 + 5 = {myResult}");

myResult= Subtract(5, 5);
Console.WriteLine($"5 - 5 = {myResult}");
}

static int Add(int a, int b)
{
return a + b;
}

static int Subtract(int a, int b)
{
return a - b;
}

}
}
namespace FieldsAndInstanceVariables
{
internal class Program
{
// As the variable is declared in the class and not a method, it's a 'field'
// This can be used throughout the class
static int myResult;

static void Main(string[] args)
{
myResult= Add(5, 5);
Console.WriteLine($"5 + 5 = {myResult}");

myResult= Subtract(5, 5);
Console.WriteLine($"5 - 5 = {myResult}");
}

static int Add(int a, int b)
{
return a + b;
}

static int Subtract(int a, int b)
{
return a - b;
}

}
}
In the video, the code is pretty much the same. With the exception of 'myResult' not being marked as static. They are not calling an instance of the class or anything, and it's confusing me. Unless they have errors turned off or something...?
6 Replies
ティナ
ティナ5d ago
are they programming on ide or online platform? some online platform may not have error highlighting
GeorgieDoDa
GeorgieDoDaOP5d ago
They are using VS2022
Luc ♡
Luc ♡5d ago
so if i understand correctly, in the course they show the exact same code as yours, with the exception of the static missing on the int myResult? if so, that doesnt work since your accessing this field from a static method (Main)
Jimmacle
Jimmacle5d ago
static methods cannot access non-static fields (or any other instance members), so you either have to make the field static as you did or make your method non-static the reason is that static means "this doesn't belong to any particular instance of the object" so when you try to access an instance field from a static method it doesn't know which instance to get data from also as a consequence, if you make multiple instances of the same class then any static data is effectively shared between them
GeorgieDoDa
GeorgieDoDaOP5d ago
That's why I was confused as on the video, the variable wasn't marked as static. He didn't run the code though, so I'm going to assume it would fail :D. Thanks for the explanation, Jimmacle! Much appreciated!

Did you find this page helpful?