Static vars not seen too often in C #

I am new to C # - this is almost my first program. I am trying to create some public static variables and constants for use anywhere in the program. The wrong way I've tried is to declare them in a separate class in the same namespace, but they don't match the context for the main program. This is a WPF application. The code looks like this:

namespace testXyz
{
    class PublicVars
    {
        public const int BuffOneLength = 10000;
        public static int[] Buff1 = new int[BuffOneLength];

        public const int BuffTwoLength = 2500;
        public static int[] Buff2 = new int[BuffTwoLength];

        private void fillBuff1()
        {
            Buff1[0] = 8;
            Buff1[1] = 3;           
            //etc
        }

        private void fillBuff2()
        {
            Buff2[0] = 5;
            Buff2[1] = 7;           
            //etc
        }   
    }
}

      

Second file:

namespace testXyz
{
    public partial class MainWindow : Window
    {
        public MainWindow() 
        {
            InitializeComponent();
        }

        public static int isInContext = 0;
        int jjj = 0, mmm = 0;

        private void doSomething()
        {
            isInContext = 5;    // this compiles
            if (jjj < BuffOneLength)    // "the name 'BuffOneLength' does not exist in the current context"
            {
                mmm = Buff2[0]; // "the name 'Buff2' does not exist in the current context"
            }
        }
    }
}

      

My actual program is much longer, of course. I created the above WPF application exactly as shown in order to test this issue and I got these errors also encountered in a real program. I really don't want to fill the arrays in the main program as they are very long and that would mean a lot of scrolling. I also want to have one place where I can declare certain public static variables. What is the correct way to do this?

+3


source to share


2 answers


You either need to specify the class:

// BuffOneLength from PublicVars class
if (jjj < PublicVars.BuffOneLength)  {
  ...
  // Buff2 from PublicVars class 
  mmm = PublicVars.Buff2[0];

      



or put with static :

// When class is not specified, try PublicVars class
using static testXyz.PublicVars;

namespace testXyz {
  public partial class MainWindow : Window {
    ...

    // BuffOneLength - class is not specified, PublicVars will be tried  
    if (jjj < BuffOneLength) {
      mmm = Buff2[0]; 

      

+8


source


You cannot access a static variable that is in another class by simply calling the variable. You need to first pass the class that contains it in your case, this will be

PublicVars.BuffOneLength

      



and

PublicVars.Buff2[0]

      

+2


source







All Articles