Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge 2 classes into one class at runtime

Tags:

c#

asp.net

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.

like image 211
DevMania Avatar asked Feb 03 '26 05:02

DevMania


1 Answers

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.

like image 187
Marc Gravell Avatar answered Feb 05 '26 18:02

Marc Gravell