Search code examples
c#classglobal-variables

C# In codebehind, how reference public variable in another class within the same namespace?


I have a code behind that has two classes within the same namespace. I'd like to reference the first classes public variables from the second class in the namespace. I know I could obviously pass the variables, but I'd like to know if there is a way to reference them.

namespace CADE.results
{
    public partial class benchmark : BasePage
    {
        public string numAnswers = "";   <-- like to reference this from GetScore()

        protected void Page_Load(object sender, EventArgs e)
        {
            BenchmarkAdd bma = new BenchmarkAdd();
            bma.GetScore();
        }
    }


    public class BenchmarkAdd
    {
        public BenchmarkAdd() 
        { 
        }
        public void GetScore() 
        {
            benchmark.numAnswers++;    <-- would like to reference public var here
        }
    }

}

I thought just benchmark.numAnswers would work but it doesn't. Is it possible to reference numAnswers from the BenchmarkAdd class?


Solution

  • I'd like to reference the first classes public variables from the second class in the namespace.

    Well numAnswers is an instance variable, so GetScore() isn't going to know which instance to update.

    The only way this can be done (without passing your Page instance, or passing numAnswers using ref) is to make numAnswers static:

    public static string numAnswers = "";
    

    Which you could then update in GetScore():

    public void GetScore() 
    {
        CADE.results.benchmark.numAnswers++;
    }
    

    However, the effect of making this static is that each benchmark instance no longer has it's own numAnswers field; there would be only one copy of the field which would instead belong to the type itself.