Home > Net >  How can i Access a private variable in another class in C#
How can i Access a private variable in another class in C#

Time:10-04

I wrote the code below and i want to access the private varibale in another class, i created instance of the class and tried to access it but couldn't. can someone point out what I did wrong in the code below?

using System;


namespace lab_first
{
    public class AccessModifiers
    {
        private int Abc { get; set; }
        private int bcd { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            
            var acc = new AccessModifiers();
           Console.WriteLine(acc.Abc)

      
        }
    }
}

CodePudding user response:

You make members private so that nobody outside the class can access them. This goes inline with the principle of information hiding.

Your example should look like this:

public class AccessModifiers
{
    // You can only access this inside of the class AccessModifiers
    private int Abc { get; set; }
    
    internal void SetValue(int x){
        // Access possible, because SetValue() is inside the same class
        Abc = x;
    }
    
    internal int GetValue(){
        // Access possible, because GetValue() is inside the same class
        return Abc;
    }
}
class Program
{
    static void Main(string[] args)
    {
        
        var acc = new AccessModifiers();
        // Abc is never modified directly, only indirectly.
        acc.SetValue(5);
        Console.WriteLine(acc.GetValue());      
    }
}

However, there is still a way to access the private member. It's called Reflection. However, note that private variables are considered an implementation detail and might change at any time, so you can't rely on it. E.g. someone might change the name from Abc to def and your Reflection-based approach fails.

CodePudding user response:

You can either change private to internal or public in this case.

Another way is declaring the variables in the class as private and using C# Properties in the class to set and get the values of variables. this is called encapsulation which is a protective shield that prevents the data from being accessed by the code outside this shield).

public class AccessModifiers
{
    private int _abc { get; set; }
    private int _bcd { get; set; }

   public int Abc
   {
      
     get
     {
        return _abc;    
     }
      
     set 
     {
        _abc = value;
     }
   }

    public int Bcd
    {
      
      get
      {
        return _bcd;    
      }
      
      set 
      {
        _bcd = value;
      }
    }
}
  •  Tags:  
  • c#
  • Related