Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Dynamic return type
    text
    copied!<h3>I've solved my problem</h3> <pre><code> public virtual T GenerateCommand() { Type typeParameterType = typeof(T); if (typeParameterType == typeof(SqlCommand)) { //SqlCommand } else if (typeParameterType == typeof(MySqlCommand)) { //MySqlCommand } return new T() { }; } </code></pre> <p>I'm building a class that generates Queries/Commands, the class has the ability to generate various DbCommands (MsSqlServer &amp; MySql) when the type of the database is defined in field of the class. How can I return the correct type?</p> <p>I tried this:</p> <pre><code>public virtual DbCommand GenerateCommand() { //..... } </code></pre> <p>but I always need to convert the return value:</p> <pre><code>MySqlCommand s = this.GenerateCommand() as MySqlCommand; </code></pre> <p>I also tried this:</p> <pre><code>public virtual T GenerateCommand&lt;T&gt;() { //..... } </code></pre> <p>But it's not what I'm looking for because I cannot create an instance of DbCommand so I cannot return nothing.</p> <p>Is there some way that T will be based on stored type on my class?</p> <p>Edit: the using of generic class throw two exceptions at least:</p> <pre><code> if (T is MySqlCommand) { return new MySqlCommand(); } else { return new SqlCommand(); } </code></pre> <blockquote> <p>'T' is a 'type parameter' but is used like a 'variable'</p> <p>Cannot implicitly convert type 'MySql.Data.MySqlClient.MySqlCommand' to 'T'</p> </blockquote> <pre><code>(T)MySqlCommand() </code></pre> <p>also do not work</p> <p>Edit 2: can I do something like that?</p> <pre><code>public virtual T GenerateCommand(SqlDatabaseKind dbKind) { T = (dbKind == SqlDatabaseKind.MicrosoftSqlServer) ? SqlCommand : MySqlCommand; } </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