Guido Tarsia
Guido Tarsia

Reputation: 2172

How to create properties dynamically?

I need to create properties dynamically.
My scenario is like this:
I have many classes that derive from BaseClass. BaseClass has a dictionary where inherited classes should define stuff. Those definitions are done like this.

public string Type 
{
    get 
    {
        return dictionary["type"];
    }
    set
    {
        dictionary["type"] = value;
    }
}

I will have many inherited methods like this in my derived classes, where the name of the property is almost identical to the key that references its corresponding value in the dictionary. So my idea is to add attributes in the derived classes, starting with an underscore, to distinguish them and use them to create those properties.

  1. How would I define dynamically those properties at run-time?
  2. Is it possible to define those at compile-time? Would it make sense to do so?

Upvotes: 0

Views: 205

Answers (3)

mehmet mecek
mehmet mecek

Reputation: 2685

You can create functions dynamically as follows,

Expression<Func<int, int, string>> exp = (x, y) => (x + y).ToString();
var func = exp.Compile();
Console.WriteLine(func.Invoke(2, 3));

Also you can put them in a dictionary and use them dynamically.

Expression<Func<int, int, string>> expSum = (x, y) => (x + y).ToString();
Expression<Func<int, int, string>> expMul = (x, y) => (x*y).ToString();
Expression<Func<int, int, string>> expSub = (x, y) => (x - y).ToString();

Dictionary<string, Expression<Func<int, int, string>>> myExpressions =
    new Dictionary<string, Expression<Func<int, int, string>>>();

myExpressions.Add("summation", expSum);
myExpressions.Add("multiplication", expMul);
myExpressions.Add("subtraction", expSub);

foreach (var myExpression in myExpressions)
{
    Console.WriteLine(myExpression.Value.Compile().Invoke(2, 3));
}

Upvotes: 0

Olivier
Olivier

Reputation: 5698

To build those at compile-time under the hood (no C# behind it), see PostSharp (it allows you to define custom patterns)

But to "create" new functions, you may be interested in:

  • Expression.Compile to create delegates (dynamic methods, which are garbage collectible in .net 4.5) Pros: that's still C#. Cons: That does not allow creating types.

  • Reflection.Emit (in .Net framework) or Mono.Cecil (thirdparty) if you want to emit dynamic types or methods at runtime. Using this, a solution to your question would be to define your properties as abstract, and dynamically create a type (at runtime) which inherits from you abstract class defined in C#, an implements it automatically. Pros: VERY powerfull. Cons: You have to learn IL :)

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Unless am missing something. You can do something like this with ExpandoObject.

dynamic obj = new ExpandoObject();
obj.Type = "123";//Create Type property dynamically
Console.WriteLine(obj.Type);//Access dynamically created Type property

Upvotes: 2

Related Questions