Srecko
Srecko

Reputation: 199

C# add properties at runtime

I've read few posts, and I'm still having troubles with adding properties to a class in runtime. It should be simple, because I have a class like this:

public class MyClass
    {
        String Template;
        String Term;
     }

During runtime, I have to add few attributes, like Phone, Email (it depends...). Could someone please explain me how to add these properties during class initialization?

Srecko

Upvotes: 2

Views: 3915

Answers (3)

Random Dev
Random Dev

Reputation: 52290

you could add an dictionary with for your Key/Value-Pairs. Then if you add your attributes you just add Key = Attributename, Value = YourValue to the dictionary. Reading is as easy - just get the Value to the Key = Attributename from your dictionary.

Upvotes: 1

Botz3000
Botz3000

Reputation: 39650

I don't think adding a property is the right thing to do here. The attributes like "Email" or "Phone" are just some additional pairs of a key and a value. You could use a Dictionary, but that would prevent you from using a key more than once (more than one email address for a contact for example). So you could just as well use a List<KeyValuePair<string, string>>. Like that:

public class MyClass
{
    String Template;
    String Term;
    public List<KeyValuePair<string, string>> Attributes { get; private set; }

    public MyClass() {
        Attributes = new List<KeyValuePair<string, string>();
    }

    public void AddAttribute(string key, string value) {
        Attributes.Add(new KeyValuePair<string, string>(key, value));
    }
}

// to be used like this: 
MyClass instance = new MyClass();
instance.AddAttribute("Email", "[email protected]");
instance.AddAttribute("Phone", "555-1234");

Upvotes: 4

Tim Jarvis
Tim Jarvis

Reputation: 18825

If you have c# 4.0 you can use the Expando object.

for earlier versions of c#, the generally accepted way of doing this is to create a "property bag" i.e. a collection (or dictionary) of key value pairs

dynamic foo = new ExpandoObject();
foo.Bar = "test";

Upvotes: 3

Related Questions