SharpD
SharpD

Reputation: 111

Adding different object types to a c# 4.0 collection

I have a function that returns objects of different types based on the parameter passed to this function. Is it possible to add these different object types to a collection based on some identifier in C# 4.0? Usually we do something like this List or List but i want one collection which can add object of any type.

Upvotes: 10

Views: 22231

Answers (9)

Duanne
Duanne

Reputation: 764

You could use a Tuple of Genric Types

public Tuple<T, T> MySuperMethod()
{
   int number = 1;
   string text = "Batman";

   return new Tuple<int, string>(number, text);
}

The .NET Framework directly supports tuples with one to seven elements. In addition, you can create tuples of eight or more elements by nesting tuple objects in the Rest property of a Tuple object.

https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.100).aspx

Upvotes: 0

syb
syb

Reputation: 379

My Suggestion:

public class ParamValue
{
    object value = null;
    public ParamValue(object val)
    {
        value = val;
    }

    public string AsString()
    {
        return value.ToString();
    }

    public int AsInt()
    {
        return int.Parse(value.ToString());
    }

    public int? AsNullableInt()
    {
        int n;

        if (int.TryParse(value.ToString(), out n))
        {
            return n;
        }

        return null;
    }

    public bool AsBool()
    {
        return bool.Parse(value.ToString());
    }

    public bool? AsNullableBool()
    {
        bool b;

        if (bool.TryParse(value.ToString(), out b))
        {
            return b;
        }

        return null;
    }
}

public class Params
{
    Dictionary<string, object> paramCol = new Dictionary<string, object>();

    public void Add(string paramName, object value)
    {
        paramCol.Add(paramName, value);
    }

    public ParamValue this[string paramName]
    {
        get
        {
            object v;

            if (paramCol.TryGetValue(paramName, out v))
            {
                return new ParamValue(v);
            }

            return null;
        }
    }
}

Use param class as a collectio to your values, you can convert the return to every type you want.

Upvotes: 0

James Westgate
James Westgate

Reputation: 11454

Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.

Upvotes: 13

Binary Worrier
Binary Worrier

Reputation: 51711

Really your collection should be as specific as you can make it. When you say

objects of different types

Do these objects have anything in common? Do they implement a common interface?
If so you you can specialise the list on that interface List<IMyInterface>

Otherwise List<object> will do what you want.

Update

No, not really.

I'm sorry but I'm going to question your design.
If you have a collection of different objects, how do you decide how to use one of the objects?
You're going to have a large switch statement switching on the type of the object, then you cast to a specific object and use it.

You also have have a similar switch statement in your factory method that creates the object.

One of the benefits of Object Orientation is that if you design your objects correctly then you don't need to do these large "If it's this object do this.Method(), if it's that object do that.OtherMethod()".

Can I ask, why are you putting different objects into the same collection? What's the benefit to you?

Upvotes: 4

Faruz
Faruz

Reputation: 9959

Also check out Dynamic type.

http://msdn.microsoft.com/en-us/library/dd264736.aspx

It will basically do the same thing.

Upvotes: 1

LLS
LLS

Reputation: 2228

Collections in earlier versions of C# (not generics) can contain any kind of objects. If they're value type, they will be boxed into object. When you need to use them, you can just cast it to the original type.

You may use List<Type> to hold the type information, if that's what you want. And Type[], Hashtable, etc. are also fine. You can use typeof operator to get the type or use Object.GetType().

Upvotes: 1

JaredPar
JaredPar

Reputation: 755141

If you want a collection which can add objects of any type then List<object> is the most appropriate type.

Upvotes: 2

leppie
leppie

Reputation: 117280

Yes, it is called object. Eg:

var objlist = new List<object>();
objlist.Add(1);
objlist.Add(true);
objlist.Add("hello");

Upvotes: 9

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

You could use object[], List<object>, ArrayList, IEnumerable, ... but if those types have a common base type it would be better to stick to a strongly typed collection.

Upvotes: 5

Related Questions