user3715648
user3715648

Reputation: 1588

Can you dynamically add a property to an object in C#?

I have a class FooBar. I use this class all over my codebase and want to keep it clean. I'm currently working with FooBar in such a way that I have a list of FooBars and a list of values. I need to iterate through the list and match values to FooBar elements. There will be multiple values associated to a single FooBar. Is there some way I can temporarily add a list to my FooBar objects so I can just append the values to this list? Something like this:

List <FooBar> myFoos = GetFoos();
List <int> values = GetValues();
foreach (var value in values)
{
    foreach (var foo in myFoos)
    {
        if (CheckMatch(foo, value))
        {
            if (foo.tempList == null)
            {
                foo.tempList = new List<int>();
            }
            foo.tempList.Add(value);
        }
    }
}
//...
//do things with the list of values on each FooBar

Right now i'm instead just creating a new Dictionary of < FooBar, List< int >>. Is creating a Dictionary just the right way to do this, or can I do something similar to what I posted above?

Upvotes: 3

Views: 584

Answers (4)

gfish3000
gfish3000

Reputation: 1567

You can create a dynamic property if you want by using Reflection but that may not necessarily be the best approach for your problem.

If you have a class used all over your codebase and you need to match it to a list of values, but it lacks the capacity to hold these values, you should re-think your design. Depending on where you get these values, you might want to either get the reference to the particular instance of FooBar or consider a class which inherits from FooBar or holds these values and then gets an id property from the FooBar instance.

Upvotes: 0

Frement
Frement

Reputation: 766

No, you can't dynamically add properties to an object. I can't tell you if what you currently have, is the best way to do it, since I don't know what you're trying to do. If you can shed some light on where and how this code is used, I can give a better answer.

Upvotes: 0

DanielCuadra
DanielCuadra

Reputation: 1030

There are several options, depending of what you need. Either Dictionary<FooBar, List<int>> or Dictionary<FooBar, HashSet<int>> can be used.

Or you could use a HashSet<KeyValuePair<FooBar, int>>.

It all depends of the type of constraint you require.

Maybe you should create your own class deriving from one of the proposed types in order to make your overall code slimmer.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 157098

You can use the ExpandoObject for that, which is in fact nothing more than a Dictionary<string, object>.

dynamic instance = new ExpandoObject();
instance.tempList = new List<int>();

instance.tempList.Add(1);

Of course, using a temporary Dictionary<FooBar, List<int>> is just that easy.

Upvotes: 3

Related Questions