Altering property values using Reflection

By Sockreg on Dec 06, 2009

Illustrates how you can take benefit of the System.Reflection namespace to alter object properties

/*
Author: Sockreg
Occupation: Student, .NET Enthusiast
Functionality: Illustrates how you can take benefit of the System.Reflection namespace to alter 
object properties.
*/

using System;
using System.Linq;
using System.Reflection;

class Program {

    static void Main(string[] args) {
        var newStudent = new Student() { Name="Unknown", 
                                         Surname="Washington", 
                                         ClassName="Legends", 
                                         Locality="Mount Vernon" };

        Type studentType = newStudent.GetType();
        foreach (PropertyInfo studentInfo in studentType.GetProperties()) {
            Console.WriteLine("{0} : {1}", studentInfo.Name, 
                            studentType.GetProperty(studentInfo.Name).GetValue(newStudent, null));
        }
        //setting property values via reflection
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Altering value for Name property ...");
        studentType.GetProperty("Name").SetValue(newStudent, "Denzel", null);

        //retrieving property values via reflection
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine(String.Format("Retrieved name via reflection: {0}", 
            studentType.GetProperty("Name").GetValue(newStudent, null)));

        //new student Property values
        Console.WriteLine(Environment.NewLine);
        foreach (PropertyInfo studentInfo in studentType.GetProperties()) {
            Console.WriteLine("{0} : {1}", studentInfo.Name, 
                            studentType.GetProperty(studentInfo.Name).GetValue(newStudent, null));
        }

        /*
         Splitting the ToString object method 
         and searching for a value that starts with M
        */
        Console.WriteLine(Environment.NewLine);
        var detailsArray = newStudent.ToString().Split('|');
        foreach (string studentDetail in (from studentDetail in detailsArray where studentDetail.StartsWith("M") 
                                          select studentDetail)) {
            Console.WriteLine("Found: " + studentDetail.ToString());
        }
        Console.ReadLine();
    }

}

// New student class 
class Student {
    public string Name { get; set; }
    public string Surname { get; set; }
    public string ClassName { get; set; }
    public string Locality { get; set; }

    public override string ToString() {
        return String.Format("{0}|{1}|{2}|{3}", Name, 
            Surname, ClassName, Locality);
    }
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.