[Solved] How can i Access a private variable in another class in C#


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.

0

solved How can i Access a private variable in another class in C#