473,587 Members | 2,547 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics and Type casting.

Hi all,

I have interface declared like

public IBaseInterface
{
}

then a generic collection like

public GCollection<T> Where T:IBaseInterfac e
{
}
then i have a class like

public class Address:IBaseIn terface
{}
so i declare a collection of Address type

GCollection<Add ress> mcol = new GCollection<Add ress>();

then i try to type cast it to

GCollection<IBa seInterface> mysecondcol = (GCollection<IB aseInterface>)
mcol; // this throws type cast exception !

can someone explain why this is not allowed and what can be a way around ?

TIA
Feb 14 '06 #1
8 3328
Ashish,

You would have to declare the GCollection<Add ress> as
GCollection<IBa seInterface>.

The reason you have to do this is say you could perform the cast. Then,
when you try to add another class which implements IBaseInterface, but is
not Address, you would get an exception because of the invalid cast.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Ashish" <as*****@thisis junk.com> wrote in message
news:u4******** *****@tk2msftng p13.phx.gbl...
Hi all,

I have interface declared like

public IBaseInterface
{
}

then a generic collection like

public GCollection<T> Where T:IBaseInterfac e
{
}
then i have a class like

public class Address:IBaseIn terface
{}
so i declare a collection of Address type

GCollection<Add ress> mcol = new GCollection<Add ress>();

then i try to type cast it to

GCollection<IBa seInterface> mysecondcol = (GCollection<IB aseInterface>)
mcol; // this throws type cast exception !

can someone explain why this is not allowed and what can be a way around ?

TIA

Feb 14 '06 #2
Ashish <as*****@thisis junk.com> wrote:

<snip>
so i declare a collection of Address type

GCollection<Add ress> mcol = new GCollection<Add ress>();

then i try to type cast it to

GCollection<IBa seInterface> mysecondcol = (GCollection<IB aseInterface>)
mcol; // this throws type cast exception !

can someone explain why this is not allowed and what can be a way around ?


Does it even compile? I'd be surprised.

Generics aren't covariant in that way - and for good reason. Imagine
you wrote the code above, and then:

mysecondcol[0] = new SomeOtherImplem entationOfIBase Interface();

That will compile, but at runtime it would either have to throw an
exception, or end up with mcol not *really* being a collection of
Address.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 14 '06 #3
hi Nicholas,
thanks for the reply,

this compiles properly but throws error at runtime, i can understand if
i try to add object of some other class and it throws error, but
IBaseEntity is a braoder type of Address so i should be able to hold a
reference ....

TIA

Nicholas Paldino [.NET/C# MVP] wrote:
Ashish,

You would have to declare the GCollection<Add ress> as
GCollection<IBa seInterface>.

The reason you have to do this is say you could perform the cast. Then,
when you try to add another class which implements IBaseInterface, but is
not Address, you would get an exception because of the invalid cast.

Hope this helps.

Feb 14 '06 #4
it compiles properly, and its okay if this throws runtime error on

mysecondcol[0] = new SomeOtherImplem entationOfIBase Interface();

but i should be able to hold a reference since Address is a narrower
type of IBaseEntity...

Jon Skeet [C# MVP] wrote:
Ashish <as*****@thisis junk.com> wrote:

<snip>
so i declare a collection of Address type

GCollection<A ddress> mcol = new GCollection<Add ress>();

then i try to type cast it to

GCollection<I BaseInterface> mysecondcol = (GCollection<IB aseInterface>)
mcol; // this throws type cast exception !

can someone explain why this is not allowed and what can be a way around ?

Does it even compile? I'd be surprised.

Generics aren't covariant in that way - and for good reason. Imagine
you wrote the code above, and then:

mysecondcol[0] = new SomeOtherImplem entationOfIBase Interface();

That will compile, but at runtime it would either have to throw an
exception, or end up with mcol not *really* being a collection of
Address.

Feb 14 '06 #5
Ashish,

No, you shouldn't. There is no relation between
GCollection<IBa seInterface> and GCollection<Add ress>. The relation of the
type parameters does not ensure that you can cast between the two.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Ashish" <as*****@thisis junk.com> wrote in message
news:e1******** *****@TK2MSFTNG P15.phx.gbl...
it compiles properly, and its okay if this throws runtime error on

mysecondcol[0] = new SomeOtherImplem entationOfIBase Interface();

but i should be able to hold a reference since Address is a narrower type
of IBaseEntity...

Jon Skeet [C# MVP] wrote:
Ashish <as*****@thisis junk.com> wrote:

<snip>
so i declare a collection of Address type

GCollection< Address> mcol = new GCollection<Add ress>();

then i try to type cast it to

GCollection< IBaseInterface> mysecondcol = (GCollection<IB aseInterface>)
mcol; // this throws type cast exception !

can someone explain why this is not allowed and what can be a way around
?

Does it even compile? I'd be surprised.

Generics aren't covariant in that way - and for good reason. Imagine you
wrote the code above, and then:

mysecondcol[0] = new SomeOtherImplem entationOfIBase Interface();

That will compile, but at runtime it would either have to throw an
exception, or end up with mcol not *really* being a collection of
Address.

Feb 14 '06 #6
Ashish wrote:
it's okay if this throws runtime error on

mysecondcol[0] = new SomeOtherImplem entationOfIBase Interface();

but i should be able to hold a reference since Address is a narrower
type of IBaseEntity...


No, you shouldn't, because the whole point of generics is to catch
these things at compile time and therefore to avoid having to generate
code to trap invalid casts at runtime (which costs). If you were
allowed to do what you're proposing, then everywhere you used a generic
structure the compiler would also have to write in run-time type
checking, which would slow things down considerably.

You're looking at the from the point of view of a reader: "If I'm going
to read this collection, I don't care whether it's declared to be a
collection of type A, or a collection of some base type of A." All well
and good, but for the purposes of writing to the collection, it does
matter.

Don't forget: there's already a way to have a collection that you can
regulate using run-time type checking of its contents: use an
ArrayList. Remember that in the 1.1 world there were collections in
which you could place any type of object and you took care of type
checking yourself.

In the 2.0 world, generics added the capability to have collections
that were locked down to a particular type (or any type derived from
that particular type). There is no capability to "broaden the scope" of
what's allowed in the collection for certain purposes. A collection is
of a particular type and that's all there is to it. Any relaxation of
that rule comes with (undesirable) run-time costs.

The only reasonable exception I can see would be to allow you to cast a
*read-only* collection of class A to a *read-only* collection of any
ancestor of class A, but that's probably too specific to justify the
work it would take to shoehorn it into the language.

Feb 14 '06 #7
I see your point, but in my logic i dont know what type the collection
would be, apart from that it would be a type implementing IBaseEntity,

Is there a work around i could implement so somehow type cast into a
more generic collection ?

thanks again for your help

regards

Nicholas Paldino [.NET/C# MVP] wrote:
Ashish,

No, you shouldn't. There is no relation between
GCollection<IBa seInterface> and GCollection<Add ress>. The relation of the
type parameters does not ensure that you can cast between the two.

Feb 14 '06 #8
Ashish <as*****@thisis junk.com> wrote:
it compiles properly


Please provide the code then. Here's some code which *doesn't* compile,
which is very similar to your code:

using System;
using System.IO;
using System.Collecti ons.Generic;

class Test
{
static void Main (string[] args)
{
List<MemoryStre am> m = new List<MemoryStre am>();
List<IDisposabl e> i = (List<IDisposab le>)m;
}
}

That's about as close to your code as I can get without seeing the
definition of GCollection etc.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 14 '06 #9

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

Similar topics

4
25401
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the following error: Argument '1': cannot convert from 'GenericsPOC.ArticleCollection' to 'System.Collections.Generic.IList<object>' I tried casting...
7
3482
by: Gene Vital | last post by:
Hi all, I need some help in understanding how to use Generics. I have a class based on a user control that can be put on any Container at runtime, I want to be able to call a method on the parent class without knowing the type of the parent class, can this be done with C#? I thought this was what Generics was supposed to be all about but...
8
2412
by: Kris Jennings | last post by:
Hi, I am trying to create a new generic class and am having trouble casting a generic type to a specific type. For example, public class MyClass<Twhere T : MyItemClass, new() { public MyClass() { } public void AppendItem()
7
2198
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
1805
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 DerivedList that can hold items of the type DerivedItem, which inherits from BaseList. So far so good... But if I somehow get an object that I know is...
13
3809
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The...
4
1937
by: Random | last post by:
I want to define a generics method so the user can determine what type they expect returned from the method. By examining the generics argument, I would determine the operation that needs to be performed and do just that. However, out of the two possible ways of doing this, neither seems to work. I thought I could either... 1) overload...
3
2722
by: =?Utf-8?B?RnJhbmsgVXJheQ==?= | last post by:
Hi all I have some problems with Crystal Reports (Version 10.2, Runtime 2.0). In Section3 I have added a OLE Object (Bitmap). Now when I open the report in my code I would like to set this OLE Object (load a picture from a given path). Something like this I would expect: _reports.crImage local_Report = new _reports.crImage();
3
1294
by: Anders Borum | last post by:
Hello, I've worked on an API for quite some time and have (on several occasions) tried to introduce generics at the core abstract level of business objects (especially a hierarchical node). The current non-generic implementation is functional, but not as clean as I would like. Although not sure, I believe my problems stem from lacking...
8
1466
by: Tony Johansson | last post by:
Hello! I have read that in practice, casting proved to be several times faster than using a generic. So the main reason to use generics is not that the performance is better because that's not the case. The only reason is that it's type-safe. I must ask if anyone has made any significant performance improvement using
0
7849
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8347
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6626
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5718
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3844
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2358
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1189
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.