As an option, you can make your own attribute through which you will establish the type SessionType between Session and SessionType :
[AttributeUsage(AttributeTargets.Class)] public class SessionAttribute : Attribute { public SessionAttribute(Type type) { Type = type; } public Type Type { get; } }
We decorate with our attribute SessionType :
public class FirstSession : Session { public override SessionType SessionType => new FirstSessionType(); } public class SecondSession : Session { public override SessionType SessionType => new SecondSessionType(); } [Session(typeof(FirstSession))] public class FirstSessionType : SessionType { } [Session(typeof(SecondSession))] public class SecondSessionType : SessionType { }
After that, you can create an instance of Session knowing SessionType :
public static Session CreateInstanceOfSession(Type sessionType) { var attr = sessionType.GetCustomAttribute(typeof(SessionAttribute)) as SessionAttribute; if (attr != null) { return (Session)Activator.CreateInstance(attr.Type); } return null; }
Checking:
Console.WriteLine(CreateInstanceOfSession(typeof(FirstSessionType)).ToString()); //Выведет FirstSession Console.WriteLine(CreateInstanceOfSession(typeof(SecondSessionType)).ToString()); //Выведет SecondSession