The following code gives me errors:
Cannot implicitly convert type T to string. Cannot implicitly convert type T to int.
What do I need to do so that this method returns the type of the variable that I define with T when I call it?
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<string>("firstName")); Console.WriteLine("his age is {0}", GetPropertyValue<int>("age")); } public static T GetPropertyValue<T>(string propertyIdCode) { if (propertyIdCode == "firstName") return "Jim"; if (propertyIdCode == "age") return 32; return null; } } }
Addendum:
Here is a more complete example of why I needed a general solution, i.e. I have a class that stores its values โโas strings regardless of type, and this general solution just makes the cleaning code:
using System; using System.Collections.Generic; namespace TestGener234 { class Program { static void Main(string[] args) { List<Item> items = Item.GetItems(); foreach (var item in items) { string firstName = item.GetPropertyValue<string>("firstName"); int age = item.GetPropertyValue<int>("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<Item> GetItems() { List<Item> items = new List<Item>(); items.Add(new Item { FirstName = "Jim", Age = "34" }); items.Add(new Item { FirstName = "Angie", Age = "32" }); return items; } public T GetPropertyValue<T>(string propertyIdCode) { if (propertyIdCode == "firstName") return (T)(object)FirstName; if (propertyIdCode == "age") return (T)(object)(Convert.ToInt32(Age)); return default(T); } } }
source share