Travis J
Travis J

Reputation: 82297

How can inheritance be applied to a group of classes once

In c#, I would like the abstract class to be applied to many other classes. How can I do it without marking each class.

public abstract class Bar
{
 public bool Blah { get; set; }
}

public class Foo : Bar
{
 public int FooId { get; set; }
}

public class Stool : Bar {}
public class Fun : Bar {}
public class NoFun : Bar {}

etc, etc.

Is there a way to just grab every class and then mark it as inheriting Bar?

Upvotes: 3

Views: 108

Answers (2)

Sean Thoman
Sean Thoman

Reputation: 7489

Aside from using templates and/or a VS add-in as the other posters mentioned, it is technically possible to do this with Reflection.Emit, though it'd be quite laborious and probably not very performant. It could come down to IL manipulation and having to create a function that manually maps the IL from the base class onto the new dynamic type.

If you can use an interface instead of an abstract class that could be a bit easier. Here is some sample code to get you started either way:

    AssemblyName assemblyName = new AssemblyName("MyDynamicAssembly");

    AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly
        (assemblyName, AssemblyBuilderAccess.RunAndSave);

    ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule
        ("MyDynamicAssembly", "MyDynamicAssembly.dll");

    TypeBuilder typeBuilder = moduleBuilder.DefineType
        ("MyDynamicAssembly." + typeName, TypeAttributes.Public, typeof(object));

    typeBuilder.AddInterfaceImplementation(typeof(IMyInterface)); 

    typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);

Upvotes: 1

Servy
Servy

Reputation: 203827

No. You could have a visual studio add-in that did this, or some other similar sort of static code manipulation tool, but in terms of the language itself there is no way to modify the inheritance of a type at runtime, and as far as I know of no existing visual studio functionality for doing this for you.

Upvotes: 4

Related Questions