C#, Generics and casting

  • Thread starter Thread starter krahenbuhl
  • Start date Start date
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
 
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
 
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
 
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?
 
Back
Top