cast

F

Frank

Hello,
I don't know how to do the following.
In a method I get a parameter with type object. These can be about 10
different types and I want to store the object in a list with the correct
type (so, not type object, but type A or B or C). I could use a switch on
gettype and then do a cast and put it in the list. But if new types are
added I have to change this method and I am too lazy to do that. I need
something like:
list.add((gettype(object))object)
The '(gettype(object))' is meant as a cast, but this is not possible in c#.
How can I add the correct type in a generic way? So I don't need to change
anything if a new type is created.

Thanks
Frank
 
J

Jon Skeet [C# MVP]

I don't know how to do the following.
In a method I get a parameter with type object. These can be about 10
different types and I want to store the object in a list with the correct
type (so, not type object, but type A or B or C). I could use a switch on
gettype and then do a cast and put it in the list. But if new types are
added I have to change this method and I am too lazy to do that. I need
something like:
list.add((gettype(object))object)
The '(gettype(object))' is meant as a cast, but this is not possible in c#.
How can I add the correct type in a generic way? So I don't need to change
anything if a new type is created.

What's the type of your list? If you're adding it to the same list
whatever happens, then just add it as it is. Casting wouldn't actually
change the type of the object anyway.

If you could provide a short but complete program which demonstrates
the problem, that would make things clearer.

See http://pobox.com/~skeet/csharp/complete.html for what I mean by
that.

Jon
 
M

madhatter2647

This might sound stupid, but why not just create a list of objects, to
which you can add whatever you'd like, and let the function that gets
the data from the list perform the cast?
 
F

Frank

you are absolutely right, it's a stupid question. I didn't think of the
consequences.
Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top