call a private property on an instance of a class in csharp

To access a private property on an instance of a class in C#, you can use reflection. Reflection allows you to inspect and manipulate metadata about types, objects, methods, and other members in your code.

Here is an example of calling a private property on an instance of a class using reflection:

main.cs
using System.Reflection;

public class MyClass
{
    private int myPrivateProperty = 42;
}

// Instantiate a new instance of MyClass
var myObject = new MyClass();

// Get the private property
var myPrivatePropertyInfo = typeof(MyClass).GetField("myPrivateProperty", BindingFlags.Instance | BindingFlags.NonPublic);

// Set the value of the private property
myPrivatePropertyInfo.SetValue(myObject, 24);

// Get the value of the private property
var myPrivatePropertyValue = myPrivatePropertyInfo.GetValue(myObject);
516 chars
19 lines

In this example, we first create an instance of the MyClass class. We then use reflection to get the myPrivateProperty field of the MyClass type, which is a private field. We use the SetValue method to set the value of the private property to 24. We then use the GetValue method to get the value of the private property, which is now 24.

Note that accessing private properties using reflection should be used sparingly, as it can violate encapsulation and lead to brittle code.

gistlibby LogSnag