Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create dynamic properties in C#?

Tags:

c#

I am looking for a way to create a class with a set of static properties. At run time, I want to be able to add other dynamic properties to this object from the database. I'd also like to add sorting and filtering capabilities to these objects.

How do I do this in C#?

like image 838
Eatdoku Avatar asked Jun 03 '09 21:06

Eatdoku


2 Answers

You might use a dictionary, say

Dictionary<string,object> properties; 

I think in most cases where something similar is done, it's done like this.
In any case, you would not gain anything from creating a "real" property with set and get accessors, since it would be created only at run-time and you would not be using it in your code...

Here is an example, showing a possible implementation of filtering and sorting (no error checking):

using System; using System.Collections.Generic; using System.Linq;  namespace ConsoleApplication1 {      class ObjectWithProperties {         Dictionary<string, object> properties = new Dictionary<string,object>();          public object this[string name] {             get {                  if (properties.ContainsKey(name)){                     return properties[name];                 }                 return null;             }             set {                 properties[name] = value;             }         }      }      class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable {          string m_attributeName;          public Comparer(string attributeName){             m_attributeName = attributeName;         }          public int Compare(ObjectWithProperties x, ObjectWithProperties y) {             return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]);         }      }      class Program {          static void Main(string[] args) {              // create some objects and fill a list             var obj1 = new ObjectWithProperties();             obj1["test"] = 100;             var obj2 = new ObjectWithProperties();             obj2["test"] = 200;             var obj3 = new ObjectWithProperties();             obj3["test"] = 150;             var objects = new List<ObjectWithProperties>(new ObjectWithProperties[]{ obj1, obj2, obj3 });              // filtering:             Console.WriteLine("Filtering:");             var filtered = from obj in objects                          where (int)obj["test"] >= 150                          select obj;             foreach (var obj in filtered){                 Console.WriteLine(obj["test"]);             }              // sorting:             Console.WriteLine("Sorting:");             Comparer<int> c = new Comparer<int>("test");             objects.Sort(c);             foreach (var obj in objects) {                 Console.WriteLine(obj["test"]);             }         }      } } 
like image 154
Paolo Tedesco Avatar answered Sep 19 '22 14:09

Paolo Tedesco


If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing ICustomTypeDescriptor, TypeDescriptionProvider and/or TypeCoverter, you can create your own PropertyDescriptor instances at runtime. This is what controls like DataGridView, PropertyGrid etc use to display properties.

To bind to lists, you'd need ITypedList and IList; for basic sorting: IBindingList; for filtering and advanced sorting: IBindingListView; for full "new row" support (DataGridView): ICancelAddNew (phew!).

It is a lot of work though. DataTable (although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p

Here's a simple example - but you can do a lot more...

like image 37
Marc Gravell Avatar answered Sep 22 '22 14:09

Marc Gravell