473,325 Members | 2,785 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,325 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 5990
"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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.