C#, Generics and casting

K

krahenbuhl

Dear All,

I've a question related to Generics and casting in c# 2.0.
I've a class called Client which implements interface IClient.
I'd like to do:

LinkedList<Client> clients;
public LinkedList<IClient> getClients()
{
return clients;
}

but I got a casting error at compile time (even if the casting is
explicitly given). How should I do to get my list of IClient ?

Regards,

Greg
 
M

Marc Gravell

Just becase Client : IClient, it does not follow that List<Client> :
List<IClient>; as a consequence, you can't quite do what you want to here.

One option is to create a new linked list, and then populate that using
clients (not via the ctor, but manually). It really depends whether it is
critical that this is the *same list*, rather than the same contents. If so,
the only way is to declare clients as List<IClient> and cast appropriately
when you need an actual Client (rather than IClient). Or even better, just
work with IClient throughout.

The reason is that otherwise a caller could declare SomeClass : IClient,
call getClients(), and then add a SomeClass to the list; this would compile,
but would blow up at runtime as the actual clients variable cannot contain
SomeClass; better to blow up at compile time - like it is now.

Marc
 
S

Stoitcho Goutsev \(100\)

Why don't you declare the list as LinkedList<IClient> instead?
 
K

krahenbuhl

Stoitcho said:
Why don't you declare the list as LinkedList<IClient> instead?

I could (and that's what I did), but then when iterating in the list I
need to cast my IClient in Client, which is not very nice :)

Cheers,

Greg
 
?

=?iso-8859-1?Q?Lasse=20V=e5gs=e6ther=20Karlsen?=

Stoitcho said:
I could (and that's what I did), but then when iterating in the list I
need to cast my IClient in Client, which is not very nice :)

Cheers,

Greg

Why do you need to cast to the class type? Why not implement an interface
that gives you access to the pieces you want?
 

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