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.cs516 chars19 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