DevMania
DevMania

Reputation: 2341

merge 2 classes into one class at runtime

Suppose I have Class A with some properties and Attributes, and Class B with the same, how can I merge these 2 class Properties and properties Attributes into 1 class at runtime, or better is how can I add these 2 classes into a a third class as properties of this new class with their Fields, Properties, Methods, etc... at Runtime ?

Using reflection or the News .NET 4.0 Dynamic or expando Object

Edit: Damn I am sorry to all for not being clear, what I want is to create a dynamic ViewModel for MVC, where other classes are in some other assemblies, and I want them to be part of the model with their Datavalidation attributes. and I don't know how many or what exactly these classes are gonna be, so I want to iterate through assemblies and choose them then add them to the main View Model.

Upvotes: 3

Views: 6109

Answers (2)

Dr Herbie
Dr Herbie

Reputation: 3940

Assuming you don't have access to the code for either of the classes (otherwise you could just merge the code), you can create a wrapper that aggregates the two classes with the combined interfaces:

public class AandB
{
  private ClassA _instanceA = new ClassA();
  private ClassB _instanceB = new ClassB();

  public bool PropertyA
  {
    get
    {
      return _instanceA.PropertyA;
    }
    set
    {
      _instanceA.PropertyA = value;
    }
  }

  public bool PropertyB
  {
    get
    {
      return _instanceB.PropertyB;
    }
    set
    {
      _instanceB.PropertyB = value;
    }
  }
}

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062512

You can't change a type at runtime. Expando might be an option, but I am not clear how you want to interact with this object, as you would seem to be limited to reflection, and expando is not a huge friend of reflection.

It might help to clarify your requirement here, but IMO you might do better to consider loading (at runtime) a property-bag based on reflection from the two inputs; something like a Dictionary<string,object> which would let you map named keys to values.

One other thing that might be what you are after here is partial classes, but this is a single type spread over multiple source files:

partial class Foo {
    private string bar;
}
partial class Foo {
    public string Bar { get {return bar;} set {bar = value;} }
}

A final option here is TypeBuilder, but that is massive overkill in most scenarios.

Upvotes: 5

Related Questions