Following scheme works fine dealing with strings/primitives. But when dealing with lists it gives type cast error in getObj(). The types used are dynamic and needs this generic use.
Is there any better way to achieve it ?
public static Object obj;
static public T getObj<T>()
{
return (T)obj;
}
private static string getStr()
{
return "some string";
}
private static List<Object> getList()
{
List<Object> res = new List<object>();
Object o = "str1";
res.Add(o);
o = "str2";
res.Add(o);
return res;
}
public static void Main()
{
obj = getStr();
string s = getObj<string>();
obj = getList();
List<string> slist = getObj<List<string>>();
}
You’re trying to cast a
List<Object>to aList<String>. Even if all the contents of the list are ofString, theListis still aList<Object>, so you cannot do a direct cast like that.If you really want to do so, you could use this instead:
A reason you cannot do a cast from
List<Object>toList<String>is because all strings are objects but not all objects are strings; if you casted aList<String>toList<object>and then tried to add anobject(that is not astring) to it, the behaviour would be undefined.