Thread: how to create a generic T object dynamically

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    4

    how to create a generic T object dynamically

    Code:
      public T GetReposit<T>() where T : class        {
                var result = default(T);
                if (typeof(T) == typeof(UserRepository))
                {
                    result = new UserRepository(Context) as T;
                }
                if (typeof(T) == typeof(ProductRepository))
                {
                    result = (T)(object)new ProductRepository(Context);
                }
                if (typeof(T) == typeof(CustomerRepository))
                {
                    result = (T)(object)new CustomerRepository(Context);
                }
                // etc....
               
                return result;
            }
    // when i have BaseListPage
    public class BaseListPage<TEntity, TRepository> : BasePage
    					where TEntity : Tentity
    					where TRepository : BaseRepository<TEntity> {
    		protected TRepository _repository;
    
    
    		public BaseListPage() {
    			UnitOfWork unit = UnitOfWork.Instance;
    			_repository = unit.GetRepository<TRepository>();
    		}
    //it actually works but i want to optimize this code

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You can use Activator.CreateInstance():

    Code:
        result = (T)Activator.CreateInstance(typeof(T), new object[] { Context });
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    4
    Thank you my friend, you really helped me

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to create a generic Function Pointer?
    By Arshad Nazeer in forum C Programming
    Replies: 4
    Last Post: 01-08-2017, 06:18 AM
  2. Dynamically create an array?
    By Unknowntoyou000 in forum C++ Programming
    Replies: 16
    Last Post: 04-25-2008, 03:49 PM
  3. Create generic classes to be specified later?
    By jmd15 in forum C++ Programming
    Replies: 18
    Last Post: 08-05-2007, 09:21 AM
  4. Dynamically create Identifiers?
    By mcrewry in forum C Programming
    Replies: 1
    Last Post: 12-28-2006, 12:22 PM
  5. Dynamically creating an object
    By Grins2Pain in forum C++ Programming
    Replies: 4
    Last Post: 09-26-2003, 09:49 AM

Tags for this Thread