I have a requirement where I can get the following in an object –
a type T or List<T>
Converting object into T is easy. How can I convert it to List(by first checking that it can be converted successfully or not), reason I want to convert is to scroll through the list and call tostring on each element.
My actual code –
namespace Generic_Collection_Code { class Program { public static string DumpObj(object obj) { string sTemp = String.Empty; List<int> ints = obj as List<int>; if (ints != null) { foreach (int i in ints) sTemp += i.ToString() + ','; sTemp.Trim(','); } else { List<string> strings = obj as List<string>; if (strings != null) { foreach (string s in strings) sTemp += s + ','; sTemp.Trim(','); } else { sTemp += obj.ToString(); } } return sTemp; } static void Main(string[] args) { List<int> listInts = new List<int>(); listInts.Add(1); listInts.Add(2); listInts.Add(3); Console.WriteLine('Object1: {0}', DumpObj(listInts)); int i = 90; Console.WriteLine('Object2 {0}', DumpObj(i)); List<string> listStrings = new List<string>(); listStrings.Add('1'); listStrings.Add('2'); listStrings.Add('3'); Console.WriteLine('Object3: {0}', DumpObj(listStrings)); Console.ReadKey(); } } }
The above code works but I know its an ugly way to achieve this. I wanted to ask from community how can I have this function like –
public static string DumpObj<T>(object obj) { string sTemp = String.Empty; List<T> list = obj as List<T>; if (list != null) { foreach (T i in list) sTemp += i.ToString() + ','; sTemp.Trim(','); } return sTemp; }
This gives me compilation errors as I have to specify T while calling DumpObj with error as –
Error 1 The type arguments for method ‘Generic_Collection_Code.Program.DumpObj(object)’ cannot be inferred from the usage. Try specifying the type arguments explicitly. D:\DotNet\Generic_Collection_Code\Generic_Collection_Code\Program.cs 57 47 Generic_Collection_Code
as you can see, obj is an object, i dont know its type while calling dumobj.
I hope I have made myself clear on this one.
I appreciate your time!
Regards Amit
What is the compilation error you’re getting? If T is declared as a generic type parameter in your context then then the only compile-time issue I can see with that statement is the use of the keyword
objectas a variable name. At any rate, I’d suggest something like this as best expressing your intention:You may also want to consider using a StringBuilder if your list is likely to have a lot of items.