chum of chance
chum of chance

Reputation: 6290

How do I do a cast to an object type in C#?

I have a:

public class MyClass { 
 private string PrivateString; 
}

and I have an interface that accepts:

object o

I have a list of MyClass that I need to push through object o, and my Google is failing me. What's the procedure to make this work? I know this must be crazy simple, but I've yet to do type casting in C#.

Upvotes: 3

Views: 334

Answers (3)

slugster
slugster

Reputation: 49984

The List<MyClass> object can still be just passed to your interface implementation, because List can be implicitly cast down to object (as can all objects). If the compiler complains because of the way you have your code set up (i have to say that because you haven't actually shown us any code) then you can explicitly cast it:

myInterfaceFunction((object) myList);

or:

myInterfaceFunction(myList as object);

If you want to cast the contents of the list and pass a List<object> when you already have a List<MyClass> then you can just do this:

myInterfaceFunction(myList.Cast<object>().ToList());

(you can get rid of the ToList() if your interface function uses IEnumerable<object> instead of List<object>).

Here is a quick example. This has a good illustration of my comment about explicitly casting to object - by default the call to MyFunction(myList) will go to the MyFunction(IEnumerable<object> blah) function - you have to explicitly cast it to force it to go to the MyFunction(object blah) function.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<MyObject> myList = new List<MyObject>();

            MyFunction(myList);
            MyFunction((object)myList);
            MyFunction(myList.Cast<object>().ToList());
            MyFunction(myList.Cast<object>());
        }


        public static void MyFunction(List<object> blah)
        {
            Console.WriteLine(blah.GetType().ToString());
        }

        public static void MyFunction(IEnumerable<object> blah)
        {
            Console.WriteLine(blah.GetType().ToString());
        }

        public static void MyFunction(object blah) 
        {
            Console.WriteLine(blah.GetType().ToString());
        }
    }


    public class MyObject { }
}

Upvotes: 2

Rune FS
Rune FS

Reputation: 21742

You don't needed to do any type casting to use a MyClass object for a method taking an object argument however you might have problems casting a list of MyClass objects to a list of objects

Upvotes: 0

Anthony
Anthony

Reputation: 12397

MyClass my = new MyClass();
WhateverTheFunctionThatTakesObjectIs(my);

Everything will implicitly cast to object.

Upvotes: 4

Related Questions