Hi there, I want to access an object property dynamically.
Basi idea is I got a string as "oClient.Name" where oClient is an object of type Client and name is the property. How can I get a value of this property at run time?
It is something similar to Eval function we have in Jscript. Any option for C#.net developer ?
Cheers, Ricky
Vijaya KadiyalaPosted Jul 1, 2008, 4:27 PM
Hi,
Check out the below link
http://www.sitepoint.com/forums/showthread.php?t=382345
Thanks -- Vj
http://dotnetvj.blogspot.com
AlanPosted May 7, 2008, 5:04 AM
In C# you can use reflection to both create an object dynamically and to access its properties. Here's a quick example:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type t = typeof(Client);
object oClient = Activator.CreateInstance(t, new object[]{"Ricky"});
BindingFlags bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty;
string name = (string)t.InvokeMember("Name", bf, null,oClient,null);
Console.WriteLine("The name of the client is {0}", name);
Console.ReadLine();
}
}
class Client
{
private string name;
public string Name
{
get{ return name;}
set{ name = value;}
}
public Client(string name)
{
this.name = name;
}
}
As you can see, the code to do this is rather tedious though it should get better in C# 4.0 where some special syntax to deal with 'dynamic lookup' is planned :)