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
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
are they programming on ide or online platform? some online platform may not have error highlighting
They are using VS2022
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)
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 themThat'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!