title: How can I create a generic method to return a specific type specified by the call?
body: <p>The following code gives me the errors:</p>
  
  <pre><code>Cannot implicitly convert type T to string.
  Cannot implicitly convert type T to int.
  </code></pre>
  
  <p><strong>What do I have to do to get this method to return the type of variable I define with T when I call it?</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  
  namespace TestGener234
  {
      class Program
      {
          static void Main(string[] args)
          {
              Console.WriteLine("his first name is {0}", GetPropertyValue&lt;string&gt;("firstName"));
              Console.WriteLine("his age is {0}", GetPropertyValue&lt;int&gt;("age"));
          }
  
          public static T GetPropertyValue&lt;T&gt;(string propertyIdCode)
          {
              if (propertyIdCode == "firstName")
                  return "Jim";
              if (propertyIdCode == "age")
                  return 32;
              return null;
          }
      }
  }
  </code></pre>
  
  <h1>Addendum:</h1>
  
  <p><strong>Here is a more complete example of why I needed the generic solution, i.e. I have a class that saves its values as strings no matter what the type, and this generic solution simply makes the calling code cleaner:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  namespace TestGener234
  {
      class Program
      {
          static void Main(string[] args)
          {
              List&lt;Item&gt; items = Item.GetItems();
              foreach (var item in items)
              {
                  string firstName = item.GetPropertyValue&lt;string&gt;("firstName");
                  int age = item.GetPropertyValue&lt;int&gt;("age");
                  Console.WriteLine("First name is {0} and age is {1}.", firstName, age);
              }
              Console.ReadLine();
          }
      }
  
      public class Item
      {
          public string FirstName { get; set; }
          public string Age { get; set; }
  
  
          public static List&lt;Item&gt; GetItems()
          {
              List&lt;Item&gt; items = new List&lt;Item&gt;();
              items.Add(new Item { FirstName = "Jim", Age = "34" });
              items.Add(new Item { FirstName = "Angie", Age = "32" });
              return items;
          }
  
          public T GetPropertyValue&lt;T&gt;(string propertyIdCode)
          {
              if (propertyIdCode == "firstName")
                  return (T)(object)FirstName;
              if (propertyIdCode == "age")
                  return (T)(object)(Convert.ToInt32(Age));
              return default(T);
          }
      }
  }
  </code></pre>