The following code gives me the errors:
Cannot implicitly convert type T to string.
Cannot implicitly convert type T to int.
What do I have to do to get this method to return the type of variable 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 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:
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);
}
}
}