Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is "sort of" possible. Sort of in that you can do it, but it's a bit of a hack.</p> <p>You have 3 options:</p> <p>If you know your classes up front, use a switch statement. Basically like this:</p> <pre><code>switch(str){ case "TypeRepository": return new Repository&lt;TypeRepository&gt;; } </code></pre> <p>As a more advanced form of the above, you can use a dictionary instead of a hashtable</p> <pre><code>var factory = new Dictionary&lt;string, Func&lt;object&gt;&gt;(); factory.Add( "TypeRepository", () =&gt; new Repository&lt;TypeRepository&gt;() ); var theObject = factory["TypeRepository"]() as Repository&lt;TypeRepository&gt;; </code></pre> <p>For the greatest flexibility, You can use reflection to match strings to classes at runtime. Be aware that reflection is fairly slow, so if you're doing this with any kind of regularity, you want to avoid it. As an example, Here's one using <a href="https://stackoverflow.com/questions/687363/how-do-i-create-a-generic-class-from-a-string-in-c/687383#687383">Frans Bouma's</a> method. Just change <code>List&lt;&gt;</code> to <code>Repository&lt;&gt;</code> in your code:</p> <pre><code>public static object MakeList( string typeStr ) { var nameSpace = "MyTestApplication" + "."; var objType = Type.GetType(nameSpace + typeStr); // NAMESPACE IS REQUIRED var listType = typeof(List&lt;&gt;).MakeGenericType(objType); return Activator.CreateInstance(listType); } var listOfThings = MakeList("MyCoolObject") as List&lt;MyCoolObject&gt;; </code></pre> <p>Note: There's no way to avoid the fact that all these mechanisms return <code>object</code>, which you then have to cast to your proper type, rather than returning just returning strongly typed values.</p> <p>This is unavoidable, because you don't know the type of the list until runtime, and C# is built around knowing things at compile time (this is what people mean when they say "statically typed programming language"). It will be less painful in C#4, where you'll be able to return <code>dynamic</code>, which will save you the casting.</p>
 

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