473,216 Members | 1,202 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,216 software developers and data experts.

Casting generics and inherited classes in .NET 2.0

Is the following behavior correct? If so, can somebody explain why?

public interface IObservation
{
string ID { get; set;}
}
public class Observation
{
string m_ID;
string ID { get { return m_ID; } set { m_ID = value; } }
}
public class ObservationComparer : IComparer<IObservation>
{
public int Compare(IObservation x, IObservation y)
{
return string.Compare(x.ID, y.ID);
}
}
class Program
{
static void Main(string[] args)
{
List<Observation> test = new List<Observation>(); // Will cause
compile error
IList<Observation> test = new List<Observation>(); // Successful
compile
((List<IObservation>)test).Sort(new ObservationComparer());
}
}

Dec 22 '05 #1
8 5981
"Dave Booker" <db******@newsgroup.nospam> a écrit dans le message de news:
07**********************************@microsoft.com...

| List<Observation> test = new List<Observation>();

| ((List<IObservation>)test).Sort(new ObservationComparer());

If you mean, why can't you cast a List<Observation> to a List<IObservation>,
then you need to realise that just becaue Observation implements
IObservation does not imply that a List<> of one tpye can be cast to a
List<> of a derived or base type. Generic types are typesafe to the type
they are bound to.

A List<Observation> is a totally differnt type from List<IObservation>.
There is no inheritance between the two; they are two totally different
List<> types, even though the bound parameter of one does inherit from the
other.

i.e.

IObservation <- Observation // inheritance

List<IObservation> // one strict type
List<Observation> // another strict type

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 22 '05 #2
I suspected as much, but then I still don't understand why an
IList<Observation> can be cast to List<IObservation>.

"Joanna Carter [TeamB]" wrote:
If you mean, why can't you cast a List<Observation> to a List<IObservation>,
then you need to realise that just becaue Observation implements
IObservation does not imply that a List<> of one tpye can be cast to a
List<> of a derived or base type. Generic types are typesafe to the type
they are bound to.

A List<Observation> is a totally differnt type from List<IObservation>.
There is no inheritance between the two; they are two totally different
List<> types, even though the bound parameter of one does inherit from the
other.

i.e.

IObservation <- Observation // inheritance

List<IObservation> // one strict type
List<Observation> // another strict type

Joanna


Dec 22 '05 #3
Dave Booker <db******@newsgroup.nospam> wrote:
I suspected as much, but then I still don't understand why an
IList<Observation> can be cast to List<IObservation>.


It can't. It can be cast to List<Observation>, but not
List<IObservation>.

Basically the type itself still obeys polymorphism, but two types which
use different generic type parameters are completely separate.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 22 '05 #4
"Dave Booker" <db******@newsgroup.nospam> a écrit dans le message de news:
CD**********************************@microsoft.com...

|I suspected as much, but then I still don't understand why an
| IList<Observation> can be cast to List<IObservation>.

Because IList and List are related *and* IObservation can be regarded as
intrinsically the same type as any class that implements it.

Tricky, isn't it ? :-))

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 22 '05 #5
"Jon Skeet [C# MVP]" <sk***@pobox.com> a écrit dans le message de news:
MP************************@msnews.microsoft.com...

| > I suspected as much, but then I still don't understand why an
| > IList<Observation> can be cast to List<IObservation>.
|
| It can't. It can be cast to List<Observation>, but not
| List<IObservation>.

After posting my latest reply, I now recant and agree with you John. I had
compiled the test code but hadn't run it. Sure enough, it generates an
invalid typecast :-)

I take it I am correct in saying that that you can cast the generic type to
its ancestor/derivative types, but you have to maintain the parameter type
to be absolutely identical ?

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 22 '05 #6
"Joanna Carter [TeamB]" <jo****@not.for.spam> a écrit dans le message de
news: %2****************@TK2MSFTNGP10.phx.gbl...

| Because IList and List are related *and* IObservation can be regarded as
| intrinsically the same type as any class that implements it.
|
| Tricky, isn't it ? :-))

Dave, ignore this rubbish, I should have known better than to compile but
not run the test code :-))

See my reply to John's post.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 22 '05 #7
Joanna Carter [TeamB] <jo****@not.for.spam> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> a écrit dans le message de news:
MP************************@msnews.microsoft.com...

| > I suspected as much, but then I still don't understand why an
| > IList<Observation> can be cast to List<IObservation>.
|
| It can't. It can be cast to List<Observation>, but not
| List<IObservation>.

After posting my latest reply, I now recant and agree with you John. I had
compiled the test code but hadn't run it. Sure enough, it generates an
invalid typecast :-)

I take it I am correct in saying that that you can cast the generic type to
its ancestor/derivative types, but you have to maintain the parameter type
to be absolutely identical ?


Yup.

From the draft of the ECMA spec:

<quote>
No special conversions exist between constructed reference types other
than those described in §15. In particular, unlike array types,
constructed reference types do not exhibit =3Fco-variant=3F conversions..
This means that a type List<B> has no conversion (either implicit or
explicit) to List<A> even if B is derived from A. Likewise, no
conversion exists from List<B> to List<object>.

[Note: The rationale for this is simple: if a conversion to List<A> is
permitted, then apparently, one can store values of type A into the
list. However, this would break the invariant that every object in a
list of type List<B> is always a value of type B, or else unexpected
failures can occur when assigning into collection classes. end note]
</quote>

and

<quote>
A constructed class type has a direct base class, just like a simple
class type. If the generic class declaration does not specify a base
class, the base class is object. If a base class is specified in the
generic class declaration, the base class of the constructed type is
obtained by substituting, for each type-parameter in the base class
declaration, the corresponding type-argument of the constructed type.
</quote>

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 22 '05 #8
Hi ,
I just wanted to check how things are going and whether or not your
question has been resolved. If there is any question, please feel free to
join the community and we are here to support you at your convenience.
Thanks again and Happy New Year!

Best Regards,

Terry Fei[MSFT]
Microsoft Community Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Dec 28 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: c | last post by:
Hello All, I am struggling with simple casting issue within c# and would really appreciate some insight into where I am going wrong. I have two classes, ClassA and ClassB. Each implements a...
7
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b;...
4
by: Chuck Cobb | last post by:
I have a question regarding generics: Suppose I want to create some generic collection classes: Collection<Cats> c; Collection<Dogs> d; and both Cats and Dogs are inherited from a base class...
5
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have...
3
by: Showjumper | last post by:
Back in asp.net 1.1 i made custom collection classes per Karl Seguin's article On the Way to Mastering ASP.NET: Introducing Custom Entity Classes to take advantage of strongly typed data. Now with...
3
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some...
7
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
3
by: psyCK0 | last post by:
Hi all! I have a problem of casting generics to their base type. In the code below I first define a BaseList class that can hold items of any type that inherits from BaseItem. I then define a...
19
by: jan.loucka | last post by:
Hi, We're building a mapping application and inside we're using open source dll called MapServer. This dll uses object model that has quite a few classes. In our app we however need to little bit...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.