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#?
Use ExpandoObject like the ViewBag in MVC 3.
You might use a dictionary, say
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):
If it is for binding, then you can reference indexers from XAML
Here it is referencing the class indexer with the key "FullName"
Why not use an indexer with the property name as a string value passed to the indexer?
As a replacement for some of orsogufo's code, because I recently went with a dictionary for this same problem myself, here is my [] operator:
With this implementation, the setter will add new key-value pairs when you use
[]=
if they do not already exist in the dictionary.Also, for me
properties
is anIDictionary
and in constructors I initialize it tonew SortedDictionary<string, string>()
.I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!
You cannot add properties to a class after it has been JITed.
The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.
You also wouldn't be able to access those properties at compile time.
Something like:
I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)
Now you can use it:
You could also use it like a normal property in a language that supports late binding (for example, VB.NET)