ggggg
ggggg

Reputation: 49

How do I access a variable in a constructor from a method in 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)
    {
        // the usage of `a`
    }
}

Upvotes: 0

Views: 4620

Answers (3)

user147504
user147504

Reputation: 175

In your code, the scope of variable 'a' is only until the end of constructor as you declared it inside the constructor. If you want to use the variable 'a' outside the constructor, you should declare it outside the constructor but within the scope of the class.

class example
{
   private int[] a;
   public example(int x)    
   {  
      a = new int[x];
   }  

   public void method()  
   {
      for (int i = 0; i < a.Length; ++i)
      {
         // the usage of `a`
      }
   }
}

It is suggested to declare this variable as a private member so that it cannot be assigned outside the class directly.

Upvotes: 1

Sidmarconius
Sidmarconius

Reputation: 15

Method to achieve is declare it as property of that class. In constructor you should initialize private properties. So the code would look like this:

    private int[] _a {get; set;}
    public example(int x)
    {
        int[] a = new int[x];
        _a = a;
    }

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

Upvotes: 0

Cem YILMAZ
Cem YILMAZ

Reputation: 134

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.

Upvotes: 2

Related Questions