Hi, some time ago I posted information about Generic Free Pattern, but I used there the reflection. Today I would like to share with you a much faster solution. The source of creation is a bridge between non-generic and generic classes in the Creator method. The usage of the pattern is at the end of the code. Where you can create a class EntityManager that is non-generic, but the logic that is called behind the scenes redirects the execution to the generic version of this class named EntityManager. The nice thing about this pattern is that it automatically figured out the generic type T and can recognize it. Thanks for reading, and happy coding.
namespace GenericFreePatternImprovedSandbox { using System; public abstract class Entity { string Name { get; set; } public abstract string GetName(); } public class EntityManager { protected EntityManager<Entity> Manager; protected Entity Entity { get; set; } public EntityManager() { } public EntityManager(Entity entity) { if (Manager == null) { Creator(entity, out Manager); } } void Creator<T>(T entity, out EntityManager<T> manager) where T : Entity { manager = new EntityManager<T>(); manager.Entity = entity; } public virtual string GetEntityName() { return Manager.GetEntityName(); } } public class EntityManager<T> : EntityManager where T : Entity { public EntityManager() { } public EntityManager(T entity) : base(entity) { } public override string GetEntityName() { return "I am in Generic: " + Entity.GetName(); } } public class EntityTest1 : Entity { public string Name { get; set; } public override string GetName() { return "EntityTest1: " + Name; } } public class EntityTest2 : Entity { public string Text { get; set; } public override string GetName() { return "EntityTest2: " + Text; } } public class TestOfGenericFreeSolution { public static void Main() { var entity1 = new EntityTest1 { Name = "Piotr Sowa's Entity1 Name" }; var entity2 = new EntityTest2 { Text = "Piotr Sowa's Entity2 Text" }; // you are using non-generic class, but the code // is accessible from the pure generic class on. var manager1 = new EntityManager(entity1); var manager2 = new EntityManager(entity2); Console.WriteLine(manager1.GetEntityName()); Console.WriteLine(manager2.GetEntityName()); Console.ReadKey(true); } } }
p ;).