Wednesday, February 09, 2005

Assigning properties to delegates in C#

Assigning properties to delegates in C# - this cannot be done. So if you wanted to select a property to use at runtime, then you can use a method similar to that shown below. public class Class1 { string s1 = null; string s2 = null; private PropertyInfo _prop; public Class1(int iPropToUse) { if (iPropToUse == 1) _prop = typeof(Class1).GetProperty("PropOne"); else _prop = typeof(Class1).GetProperty("PropTwo"); } public string PropOne { get {return s1; } set {s1 = value;} } public string PropTwo { get {return s2;} set {s2 = value;} } public void SetStringValue(string s) { if (_prop != null) _prop.SetValue(this,s,null); } public string GetStringValue() { if (_prop != null) return (string) _prop.GetValue(this,null); else return "no property set"; } static void Main(string[] args) { Class1 o1 = new Class1(1); o1.SetStringValue("Hello"); Console.WriteLine(o1.GetStringValue()); Class1 o2 = new Class1(2); o2.SetStringValue("World"); Console.WriteLine(o2.GetStringValue()); int i = Console.Read(); } }

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.