KSav KSav - 1 year ago 141
C# Question

C# how to create class instance by class attributes

How do I create a class instance using known attributes?
In this the attributes are values of an enum.

public enum MyEnum

class MyAttribute : Attribute... //attribute definition class
{ //uses the enum}

abstract class MyMain ...
public static MyMain CreateClass
MyMain newInheritedClass = ?

class MyClassA : MyMain ...

class MyClassB : MyMain ...

Answer Source

For the purposes you describe in comments I think using attributes is little bid overkill.
Just create a static method or factory class with method which will do the same things:

public static MyMain CreateInstance(MyEnum attribute)
    if(attribute == MyEnum.Value1)
        return new MyClassA();

Of course if you have a task to create instance based on the attributes then:

private readonly Dictionary<MyEnum, Type> _Data;

public Factory(Assembly assembly) 
    var myAttributeClasses = 
                .Select(t => new 
                    DirevedType = t,
                    Attribute = (MyAttribute)t.GetCustomAttribute(typeof(MyAttribute))
                .Where(data => data.Attribute != null);

    _Data = new Dictionary<MyEnum, Type>();
    foreach(var data in myAttributeClasses)
        _Data.Add(data.Attribute.EnumValue, data.DerivedType);

public MyMain CreateInstance(MyEnum enumvalue)
    Type derivedType;
    if(_Data.TryGetValue(enumvalue, out derivedType) == false) 
        return null;

    return Activator.CreateInstance(derivedType);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download