Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't think what you're asking is possible. If your code is receiving a string that represents the generic type parameter, the type it represents can only be determined at runtime. However, generic type parameters should be specified at compile time.</p> <p>I think you'll have to instead receive the type of entity as a generic type parameter if you want to use it as a type parameter of the return type:</p> <pre><code>public IRepository&lt;TEntity&gt; MakeRepository&lt;TEntity&gt;() where TEntity : class { var repo = new TradeSiftRepository&lt;TEntity&gt;(new UnitOfWork()); return repo; } IRepository&lt;User&gt; userRepository = MakeRepository&lt;User&gt;(); </code></pre> <p>If you definitely want to receive the entity type name as a string, the responsibility of casting the result to the real type at compile time should be done by calling code, since the calling code is what specifies the type:</p> <pre><code>public object MakeRepository(string entityTypeName) { Assembly common = Assembly.LoadFrom(@"CommonLibrary.dll"); Type entityType = common.GetType(entityTypeName); Type repoType = typeof(TradeSiftRepository&lt;&gt;).MakeGenericType(entityType); var repo = Activator.CreateInstance(repoType, new UnitOfWork()); return repo; } IRepository&lt;User&gt; userRepository = (IRepository&lt;User&gt;)MakeRepository("User"); </code></pre> <p>However, the above code can be simplified by using the generic version of the method; there is less duplication. If the calling code also doesn't know what type it's asking for, I think you're out of options.</p> <p>One possible work-around is to return the dynamic type, which would leave the calling code to assume it has an object of the type its author wants:</p> <pre><code>public dynamic MakeRepository(string entityTypeName) { Assembly common = Assembly.LoadFrom(@"CommonLibrary.dll"); Type entityType = common.GetType(entityTypeName); Type repoType = typeof(TradeSiftRepository&lt;&gt;).MakeGenericType(entityType); var repo = Activator.CreateInstance(repoType, new UnitOfWork()); return repo; } dynamic userRepository = MakeRepository("ConsoleApplication1.User"); User user = userRepository.FindById(1); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload