Wednesday, November 18, 2015

Introduction to Reflection API

Set Property Value Using Reflection

1) Create new instance of Student
2) Get instance type
3) Get property FullName by name from type
4) Set property value to "John Smith" using reflection

using System;
using System.Reflection;

public class Program
{
public static void Main()
{

//1. Create new instance of Student
Student student = new Student();

//2. Get instance type
var getType = student.GetType();

//3. Get property FullName by name from type
var fullNameProperty = getType.GetProperty("FullName");//,
//typeof(string));

//4.  Set property value to "Some Name" using reflection
fullNameProperty.SetValue(student, "John Smith");

Console.WriteLine(fullNameProperty.GetValue(student)); // GetValue(sT.FullName.ToString()));

}
}

public class Student
{
public string FullName { get; set; }

public int Class { get; set; }

public DateTime DateOfBirth { get; set; }

public string GetCharacteristics()
{
return "";
}
}

No comments:

Post a Comment