Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Get set field, Properties,events or method using reflection
Posted By Sarin on Oct 08, 2012     RSS Feeds     Latest Hinduism news
3416 Views

Some times while working on your client requirements, there is a need to set /get property/ fields where this property name or field name is stored in the string. For Ex: suppose there is a property called StudentName and this property name is stored in a string called name as
String name=” StudentName”
And now you want to set property (StudentName) stored in string (name) to ‘Sarin’.  How to do this? How to set or get the property stored in string? This is where the concept of reflection comes into rescue.  This tutorial will give you a deep insight on how to get list of fields, properties, and events from objects at runtime.
First let’s create a simple class with some fields, properties, and events. Below is the class with three properties having different return types, four fields and two events.
public class ReflectionTest
     {
        //public properties
        public string StringProperty  get; set;
        public int IntProperty  get; set;
        public ReflectionTest ObjectProperty  get; set;
  
        //public fields
        public string StringField;
        public int IntField;
        public ReflectionTest ObjectField;
        private int internalField;
        //public events
        public event EventHandler Event1;
        public event EventHandler Event2;
  
        public void method1()  
        private static void method2()  
    }
  
 I will be using object of this class to demonstrate the concept of retrieving any fields, properties or methods using reflection.
.Net class which provides us access to all members of this class is the Type <https://msdn.microsoft.com/en-us/library/system.type.aspx> class. Simply create a type object using the typeof keyword:
   Type ObjectType = typeof(ReflectionTest);
  
To get all the fields, I would use the get fields method
System.Reflection.FieldInfo[] fieldInfo = ObjectType.GetFields();
  
I can then retrieve any information of these fields. As an example, I would print the field names as follows:
     foreach (System.Reflection.FieldInfo info in fieldInfo)
                Console.WriteLine(info.Name);
  
Output will look like:
// Output:
// StringField
// IntField
// ObjectField

We can also set values for these fields. As shown below, I looped through all fields to set each of the field value.

      ReflectionTest testObject = new ReflectionTest();
            foreach (System.Reflection.FieldInfo info in fieldInfo)
             {
                switch (info.Name)
                 {
                    case "StringField":
                        info.SetValue(testObject, "string value");
                        break;
                    case "IntField":
                        info.SetValue(testObject, 42);
                        break;
                    case "ObjectField":
                        info.SetValue(testObject, testObject);
                        break;
                }
            }
  
By default, only the public fields are retrieved using the above methods. What if you want to set the private, protected or internal fields? You can achieve this by adding a filtering option as shown below

FieldInfo fi = testObject.GetType().GetField("internalField", BindingFlags.NonPublic | BindingFlags.Instance);
  fi.SetValue(testObject, 12);            
   Console.WriteLine(fi.GetValue(testObject));

In above code, I requested the compiler to search for non public or instance fields.
Similarly, I can retrieve and display properties of my class as

System.Reflection.PropertyInfo[] propertyInfo =
                 ObjectType.GetProperties();            
            Console.WriteLine("---Properties----");
            foreach (System.Reflection.PropertyInfo info in propertyInfo)
                Console.WriteLine(info.Name);

Similar to the FieldInfo class, PropertyInfo class has the ability to set or get the value of any property of an instance. I can set my property as  
testObject.GetType ().GetProperty ("StringProperty").SetValue(testObject, "Bob", null);

However better way of setting property would be to have an additional check to see if the property exists

PropertyInfo prop = testObject.GetType().GetProperty("StringProperty", BindingFlags.Public | BindingFlags.Instance);
  if (null != prop && prop.CanWrite)
      {
       prop.SetValue(testObject, "StringProperty", null);
   }
  
I can print the value of my property as
  Console.WriteLine(prop.GetValue(testObject, null));

Similar to Properties and field, we have method info and event info classes to get list of all methods and events.
Below code gets and display all events

 System.Reflection.EventInfo[] eventInfo =ObjectType.GetEvents();
        foreach (System.Reflection.EventInfo info in eventInfo)
                Console.WriteLine(info.Name);
  
Similarly, below code gets and display non public and static methods
  
MethodInfo[] methodInfos = testObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance |BindingFlags.Static);
           
   foreach (System.Reflection.MethodInfo info in methodInfos)
       Console.WriteLine(info.Name);
  
Below is the output of the whole program I wrote to demonstrate the above functionalities. Check attached source code for program

This is just the basics on how to use reflection to perform basic operations. Besides the basic operation of get and set, we can also do advanced operation like invoking methods or invoking events, invoking constructors etc which is as simple as get and set operation.  
Give a like if this article was helpful to you.

Dowload Source Code
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Related Articles
Dinosaurs in ancient hinduism scriptures
kashmir main tu kanyakumari full-chennai express-english poetic translation with hindi subtitles
Ban ke Titli Dil uda-chennai express-english poetic translation with hindi subtitles
Gulabi-Shuddh desi romance english poetic translation with hindi subtitles
Tu mere agal bagal hai-Phata poster nikla hero english poetic translation with hindi subtitles
Ambarsariya-Fukrey english poetic translation with hindi subtitles
The breakpoint will not currently be hit. No symbols have been loaded for this document
Science in hinduism-Embryology in Bhagavad purana
Why lord Ganesha have elephant head
Why idols of lord Ganesha is immersed in water

Post Comment