Search This Blog

Friday, 5 July 2013

C# setting object properties through reflection and parameterised properties

So, first foray into C# today...  I wanted to use CallByName, but it turns out it's only in the VB namespace...great...  Anyway, I found that the solution lies within the System.Reflection namespace and also learned a bit about parameterised properties in C#

using System;
using System.Reflection;
 
namespace objPop
{
 
    class Program
    {
        static void Main(string[] args)
        {
            Widget w = new Widget();
            w["id"= 2;
            w["name"= "Hello";
 
            Console.WriteLine(string.Format("id={0}, name={1}"w["id"], w["name"]));
            Console.ReadKey();
        }
    }
 
 
    class Widget
    {
        public int id { getset; }
        public string name { getset; }
 
        public object this[string propName]
        {
            get { return this.GetType().GetProperty(propName).GetValue(this); }
            set { this.GetType().GetProperty(propName).SetValue(thisvalue); }
        }
        
    }
 
}

No comments:

Post a Comment