Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast an object into generic list

Tags:

c#

.net

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

like image 416
Amit Sharma Avatar asked Mar 29 '09 05:03

Amit Sharma


3 Answers

Say

List<T> genericList = object as List<T>;

if(genericList != null)
{
   // Do the loop
}

The "as" keyword verifies that "object" actually "is-a" List< T >. If so, you get a List< T > back from it. If not, you get null.

like image 83
Charlie Flowers Avatar answered Oct 20 '22 06:10

Charlie Flowers


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 object as a variable name. At any rate, I'd suggest something like this as best expressing your intention:

IEnumerable enumerable = obj as IEnumerable;

if (enumerable != null)
{
    foreach (object item in enumerable)
    {
        sTemp += item.ToString();
    }
}

You may also want to consider using a StringBuilder if your list is likely to have a lot of items.

like image 34
Dave Avatar answered Oct 20 '22 04:10

Dave


you cant do this

List<T> genericList = (List<T>)object

might be you want

List<T> genericList = (List<T>)obj

where obj is object

like image 20
Brijesh Mishra Avatar answered Oct 20 '22 04:10

Brijesh Mishra