title: Conditional typing in generic method
body: <p>Consider the following (heavily simplified) code:</p>
  
  <pre><code>public T Function&lt;T&gt;() {
      if (typeof(T) == typeof(string)) {
          return (T) (object) "hello";
      }
      ...
  }
  </code></pre>
  
  <p>It's kind of absurd to first cast to <code>object</code>, then to <code>T</code>. But the compiler has no way of knowing that the previous test assured <code>T</code> is of type <code>string</code>.</p>
  
  <p>What is the most elegant, idiomatic way of achieving this behavior in C# (which includes getting rid of the stupid <code>typeof(T) == typeof(string)</code>, since <code>T is string</code> can't be used)? </p>
  
  <hr>
  
  <p><strong>Addendum:</strong> There is no return type variance in .net, so you can't make a function overload to type string (which, by the way, is just an example, but one reason why association end redefinition in polymorphism, e.g. UML, can't be done in c#). Obviously, the following would be great, but it doesn't work:</p>
  
  <pre><code>public T Function&lt;T&gt;() {
      ...
  }
  
  public string Function&lt;string&gt;() {
      return "hello";
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Concrete Example 1:</strong> Because there's been several attacks to the fact that a generic function that tests for specific types isn't generic, I'll try to provide a more complete example. Consider the Type-Square design pattern. Here follows a snippet:</p>
  
  <pre><code>public class Entity {
    Dictionary&lt;PropertyType, object&gt; properties;
  
    public T GetTypedProperty&lt;T&gt;(PropertyType p) {
      var val = properties[p];
  
      if (typeof(T) == typeof(string) {
        (T) (object) p.ToString(this);  // magic going here
      }
  
      return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(val);
    }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Concrete Example 2:</strong> Consider the Interpreter design pattern:</p>
  
  <pre><code>public class Expression {
    public virtual object Execute() { }
  }
  
  public class StringExpression: Expression {
    public override string Execute() { }    // Error! Type variance not allowed...
  }
  </code></pre>
  
  <p>Now let's use generics in Execute to allow the caller to force a return type:</p>
  
  <pre><code>public class Expression {
    public virtual T Execute&lt;T&gt;() { 
      if(typeof(T) == typeof(string)) {  // what happens when I want a string result from a non-string expression?
         return (T) (object) do_some_magic_and_return_a_string();
      } else if(typeof(T) == typeof(bool)) { // what about bools? any number != 0 should be True. Non-empty lists should be True. Not null should be True
         return (T) (object) do_some_magic_and_return_a_bool();
      }
    }
  }
  
  public class StringExpression: Expressiong {
    public override T Execute&lt;T&gt;() where T: string {   
      return (T) string_result;
    }
  }
  </code></pre>