Live Chat Icon For mobile
Live Chat Icon

Is there a way to access private and protected members of a class instance?

Platform: WinForms| Category: General

.NET Reflection can be used to get hold of non-Public members of a class instance. The System.Type class provides various methods that allow you to access the fields/properties/methods for all defined types. Depending on the context, you can use either the typeof(class) operator or the Object.GetType() method to get hold of the System.Type object representing the particular type and then use that type object to access the required member information.

The following code shows how to use the Type.GetField() and FieldInfo.GetValue() methods to determine the value of the ’pasteIndex’ private field implemented by the Diagram.Controller class.

// In C#.NET
// Use Reflection to access the this.ActiveDiagram.Controller object’s pasteIndex private member 

Type typecontroller = typeof(Syncfusion.Windows.Forms.Diagram.Controller); 
System.Reflection.FieldInfo finfo = typecontroller.GetField('pasteIndex', BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.GetField); 
int npasteindex = 0; 
if(finfo != null) 
npasteindex = (int)finfo.GetValue(this.ActiveDiagram.Controller); 

’ Use Reflection to access the Me.ActiveDiagram.Controller object’s pasteIndex private member 

Dim typecontroller As Type = GetType(Syncfusion.Windows.Forms.Diagram.Controller)
Dim finfo As FieldInfo = typecontroller.GetType().GetField('pasteIndex', BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.GetField)
Dim npasteindex As Integer = 0
If Not finfo Is Nothing Then
   npasteindex = finfo.GetValue(Me.ActiveDiagram.Controller)
End If

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.