© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3mo ago•
9 replies
GeorgieDoDa

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...?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ static fields for struct types
C#CC# / help
4y ago
static private things(methods,fields...)
C#CC# / help
4y ago
❔ can a static class contain static class as property
C#CC# / help
3y ago
local method requires a body because it is not marked static extern?
C#CC# / help
4y ago