How do I access a variable in a constructor from a method in C#

578 views c#

I would like to access a variable (an array) declared inside a constructor from a method. How would I achieve that? In the below example, I would like to use the variable 'a'.

public example(int x)    
            int[] a = new int[x];   

public void method()  
            for (int i = 0; i < a.Length; ++i)

answered question

You could create a field int[] a

Declare 'a' as a class variable or static class variable

You can't. It doesn't work like that. You need to move that outside the constructor.

You'll have to define a field for holding it. What you've done here is declared a local variable. Once the function (in this case the constructor) is finished the variable is no longer accessible.

1 Answer


I would create a private field for a like:

private readonly int[] _a;

public Example(int x)
   _a = new int[x];

public void method()
   for(int i = 0; i < _a.Length; ++i)
   // Rest of your code

please note that if you would like to modify _a after its construction, you have to remove readonly.

posted this

Have an answer?


Please login first before posting an answer.