tags:

views:

1098

answers:

4

Hi,

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(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

+8  A: 

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.

Charlie Flowers
T will need the 'where : class' constraint for this to work.
Daniel Earwicker
Yes, that's definitely right. If you can't have the 'class' constraint, then you can say: if(typeof(List<T>).IsAssignableFrom(object.GetType())).
Charlie Flowers
I'm confused, why should T have to be a class to make a list out of it?
Dave
We're not making a list out of it. We have an object, and all we know about it is that it inherits from System.Object (as everything does). So, we're performing a runtime check to see if it actually is a List< T >. If it is, then we cast it to List< T > and then iterate it.
Charlie Flowers
BTW, the question has been edited in a way that significantly changes it. The original version had a variable of type object, and he was casting it to List< T >.
Charlie Flowers
Oh, and the part about "having to be a class" ... you cannot use the "as" operator on a value type. It has to be a reference type, which means it must have the "class" constraint.
Charlie Flowers
But List<T> isn't a value type...
Dave
Oh, and when I said "make a list out of it" I guess it would've been clearer to say "construct concrete List<>".
Dave
A: 

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.

Dave
your comment was the right answer all the way long. I was stupid enough not to IEnumerable, I kept using IEnumerable<T>. Also, I have also taken your advice of using StringBuilder into my program as it might be called large no of times.Thanks a ton for your time!
+2  A: 

you cant do this

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

might be you want

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

where obj is object

Brijesh Mishra
<pre>Actual codestring DumpObj(object obj) { List<T> glist = obj as List<T>; // cant recognize T, because its not a generic function, even if I make it as generic one, I cannot call it as at the time of sending the object I am not sure what type will it have, it might not have a list at all
I think we need to see more of your code ... several of us are interpreting it differently and it seems like the question was edited in a way that changed it. Can you increase the scope of your code sample to include the signature of the class and method you're working inside of?
Charlie Flowers
A: 

How about combining "as" with "is"?

if (object is List<T>)
{ 
  List<T> genericlist = object as List<T>;
 // loop list
}
else if (object is T)
{
 // do something else
}
Marc
If @object *is* a List<T> then you might as well just cast directly to List<T> once you know.
Dave
Have updated my question.