473,757 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Cast generic IFoo<T>

Don't mistake generic type for what you would like them to be!!

IFoo<Ahas nothing in common with IFoo<B>!
They are completely different type create dynamically at runtime.

What you ask is a bit akin to ask: "the System.Web.UI and
System.Windows. Controls namespace both contains a Control class, could I use
one in place of the other? common they have the same name!"

If you want to use a method common to both you should do as Alun suggested.
Inherhit IFoo<t: IFoo.

Surprise, surprise, it's exactly what they did at Microsoft, you'll notice,
for exemple, that
IList<T: IList
IEnumerator<T: IEnumerator
ICollection<T: ICollection
etc....

Jul 24 '08 #1
15 2387
On Jul 24, 1:30*am, "Lloyd Dupont" <some...@somewh ere.netwrote:

<snip>
Surprise, surprise, it's exactly what they did at Microsoft, you'll notice,
for exemple, that
IList<T: IList
IEnumerator<T: IEnumerator
ICollection<T: ICollection
etc....
That's only true for IEnumerator<T>. IList<Tdoesn't extent IList and
ICollection<Tdo esn't extend ICollection.

That said, making the generic interface extend a non-generic one is a
fine solution in many cases. It's what I'm doing at the moment with
Protocol Buffers...

Jon
Jul 24 '08 #2
On Wed, 23 Jul 2008 22:46:41 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
[...]
That said, making the generic interface extend a non-generic one is a
fine solution in many cases.
Noting, IMHO, that doing so assumes the non-generic interface already
exists. I'm not convinced that I'd create a non-generic interface for the
purpose (and as far as I know, Microsoft didn't either), since doing so
pretty much winds up intentionally defeating the point of using the
generic in the first place.

Whatever code's already using the generic interface in its concrete form
must already know the type parameter, so making a generic method to
support the generic interface shouldn't be a problem at all (assuming it's
not suitable for the method itself to be declared using a concrete form of
the generic interface, which I think usually would be the case).

Pete
Jul 24 '08 #3
On Jul 24, 6:57 am, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
That said, making the generic interface extend a non-generic one is a
fine solution in many cases.

Noting, IMHO, that doing so assumes the non-generic interface already
exists.
Not necessarily.
I'm not convinced that I'd create a non-generic interface for the
purpose (and as far as I know, Microsoft didn't either), since doing so
pretty much winds up intentionally defeating the point of using the
generic in the first place.
Only for some cases. It depends whether the parts of the API you're
interested in depend on the type parameter. For instance, it would be
handy for my current work if IList<Timplemen ted a (mythical)
interface called ICountable with a Count property. In my current code
I sometimes need to get the count of an object which I know is an
IList<Something but I don't know what Something is at compile-time.
Whatever code's already using the generic interface in its concrete form
must already know the type parameter, so making a generic method to
support the generic interface shouldn't be a problem at all (assuming it's
not suitable for the method itself to be declared using a concrete form of
the generic interface, which I think usually would be the case).
Not necessarily - see my example above. In my case I receive the
object as just "object" and have to cast to *something* - but there's
no appropriate type I can cast to without the type information.

In addition, I need to suppose situations where everything's dynamic -
which means my nongeneric API is actually just as rich in terms of
abilities as my generic API, it just lacks the precise type safety.
That means a lot of explicit interface implementation etc, which isn't
terribly nice but it's the best way available in the situation. I
acknowledge that it's not a terribly common situation though...

(The code is available on github -
http://github.com/jskeet/dotnet-prot...rotocolBuffers
and look at IMessage.cs and IBuilder.cs.)

Jon
Jul 24 '08 #4
For info, I've used the same non-generic/generic inherited pair many
times, for example scenarios like property bag implementations . In
reality it isn't a problem; type safety is still enforced by the
underlying type. Typically the generic interface will re-declare ("new")
some (but not all) members with more specific versions.

For example: just because List<Timplement s IList, and IList has
Add(object), that doesn't imply that you can *actually* add a string to
a List<intby cheating through the IList facet.

Marc
Jul 24 '08 #5
On Jul 24, 11:12*am, Marc Gravell <marc.grav...@g mail.comwrote:
For example: just because List<Timplement s IList, and IList has
Add(object), that doesn't imply that you can *actually* add a string to
a List<intby cheating through the IList facet.
Funnily enough, I hadn't spotted that List<Timplement s IList. I
looked at IList<Tbut not List<T>.
Hmm. That *might* be very handy...

Jon
Jul 24 '08 #6
On Wed, 23 Jul 2008 23:30:37 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
[...]
Only for some cases. It depends whether the parts of the API you're
interested in depend on the type parameter. For instance, it would be
handy for my current work if IList<Timplemen ted a (mythical)
interface called ICountable with a Count property. In my current code
I sometimes need to get the count of an object which I know is an
IList<Something but I don't know what Something is at compile-time.
If you know it's an IList<Something >, then you can use it generically and
have the call chain provide the type. That's my point.

As convenient? No, I admit not. But IMHO it's a better approach and
should be used unless it's completely impossible for some reason (having a
hard time envisioning such a scenario, but happy to give the benefit of
the doubt with respect to ruling something out completely :) ).
>Whatever code's already using the generic interface in its concrete form
must already know the type parameter, so making a generic method to
support the generic interface shouldn't be a problem at all (assuming
it's
not suitable for the method itself to be declared using a concrete form
of
the generic interface, which I think usually would be the case).

Not necessarily - see my example above. In my case I receive the
object as just "object" and have to cast to *something* - but there's
no appropriate type I can cast to without the type information.
If all you know is "object", then it doesn't really matter whether your
"ICountable " interface is inherited by "IList<T>" or is simply implemented
as a separate interface. I don't think it's necessary for the generic
interface to _inherit_ a non-generic interface for that purpose.

But in any case, this isn't comparable to the OP's scenario, which is all
I was commenting on (thus, my statement in my previous reply that included
the phrase "for the purpose").
In addition, I need to suppose situations where everything's dynamic -
which means my nongeneric API is actually just as rich in terms of
abilities as my generic API, it just lacks the precise type safety.
That means a lot of explicit interface implementation etc, which isn't
terribly nice but it's the best way available in the situation. I
acknowledge that it's not a terribly common situation though...
I admit, I'm not really clear on what "where everything's dynamic" means
in a precise way. However, I'll again suggest that's not a situation
comparable to that presented in the original post.

Pete
Jul 24 '08 #7
On Thu, 24 Jul 2008 03:12:53 -0700, Marc Gravell <ma**********@g mail.com>
wrote:
[...]
For example: just because List<Timplement s IList, and IList has
Add(object), that doesn't imply that you can *actually* add a string to
a List<intby cheating through the IList facet.
Well, you can't at run-time. But you can write code to do so that will
compile just fine.

Anyway, there seems to be some confusion that I'm saying "never inherit a
non-generic interface", which wasn't my point at all. As you all should
know, I try as hard as I can to never say "never"; there's almost always
an exception to the rule.

But with regards to the original problem, I see no need to do that.

Pete
Jul 24 '08 #8
On Jul 24, 5:36*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
If you know it's an IList<Something >, then you can use it generically and*
have the call chain provide the type. *That's my point.
No, I can't. I know it will be IList<Something in a non-compiler-
provable way, but I can't determine (at compile-time) which type it
will be. So I can't cast to it.
As convenient? *No, I admit not. *But IMHO it's a better approach and*
should be used unless it's completely impossible for some reason (having a *
hard time envisioning such a scenario, but happy to give the benefit of *
the doubt with respect to ruling something out completely :) ).
When you specify a type, e.g. as a return type or a parameter type,
you can only specify one type. You can't say "It has to take something
which implements both ICountable and IList<T>" - not unless you
introduce another generic type parameter just for that purpose, which
certainly isn't always practical.
Not necessarily - see my example above. In my case I receive the
object as just "object" and have to cast to *something* - but there's
no appropriate type I can cast to without the type information.

If all you know is "object", then it doesn't really matter whether your *
"ICountable " interface is inherited by "IList<T>" or is simply implemented *
as a separate interface.
Yes it does - because I can guarantee (in my situation) that it will
have been created as an IList<Tsomewher e. Even if the ICountable
interface existed, however I couldn't necessarily ensure that the
implementation of IList<Talso implemented ICountable.
>*I don't think it's necessary for the generic *
interface to _inherit_ a non-generic interface for that purpose.
It really, really would have helped in my situation.
But in any case, this isn't comparable to the OP's scenario, which is all*
I was commenting on (thus, my statement in my previous reply that included *
the phrase "for the purpose").
I'm not sure we know enough about the OP's scenario to say for sure.

Jon
Jul 24 '08 #9
On Thu, 24 Jul 2008 09:53:29 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
On Jul 24, 5:36Â*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
>If you know it's an IList<Something >, then you can use it generically
and Â*
have the call chain provide the type. Â*That's my point.

No, I can't. I know it will be IList<Something in a non-compiler-
provable way, but I can't determine (at compile-time) which type it
will be. So I can't cast to it.
If you don't know it in a compiler-provable way, then again: I think
that's not comparable to the OP's situation (his code specifically shows
an explicit type declaration).
[...]
>If all you know is "object", then it doesn't really matter whether your
"ICountable " interface is inherited by "IList<T>" or is simply
implemented Â*
as a separate interface.

Yes it does - because I can guarantee (in my situation) that it will
have been created as an IList<Tsomewher e. Even if the ICountable
interface existed, however I couldn't necessarily ensure that the
implementation of IList<Talso implemented ICountable.
At the risk of belaboring a point I think is irrelevant to the original
question: but why would that matter?

If as a matter of the actual definition for IList<Tit needs to inherit
ICountable, then sure...inherit away. But if all we've got is code that
wants an ICountable, then it shouldn't care at all whether that's part of
IList<Tor something else. If you already know for sure it's created as
IList<T>, then even better, should you happen to also want to use the
instance as an IList<T>. But that doesn't stop you from reinterpreting
the instance reference in two different ways to support two different
interfaces.

Again, I don't disagree that it's simpler to keep one variable than two,
but I don't see this as implying that the best solution is to create a
whole new type just for that purpose. And of course, I definitely don't
see that as a required approach to the original question.
[...]
I'm not sure we know enough about the OP's scenario to say for sure.
As is often the case, it's true that we can't be sure we know enough. I
agree with that.

But I feel reasonably confident enough to make statements based on the
question as stated. In particular, it seems pretty clear to me that he's
not looking to do any casting; he's got an object instance he wants to
pass, but without the generic decoration. In other words, the caller
already knows we're dealing with the generic type.

If his post has misrepresented the situation, then yes...there may be more
to the solution than just creating a generic method, and perhaps even
there would be a justification for creating a new non-generic interface.
But I think that given the code posted so far, a generic method is a more
appropriate approach than creating a new type.

Pete
Jul 24 '08 #10

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

Similar topics

11
5151
by: Scott Brady Drummonds | last post by:
Hi, everyone, I've checked a couple of on-line resources and am unable to determine how reinterpret_cast<> is different from static_cast<>. They both seem to perform a compile-time casting of one type to another. However, I'm certain that there is something else that is happening. Can someone explain the difference or recommend an online site that can explain it to me?
2
15950
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code comment 1). However, if I attempt to access the dictionary by using a key object that
4
52999
by: matty.hall | last post by:
I have two classes: a base class (BaseClass) and a class deriving from it (DerivedClass). I have a List<DerivedClass> that for various reasons needs to be of that type, and not a List<BaseClass>. However, I need to cast that list to a List<BaseClass> and it is not working. The code is below. I get the following exception: "Unable to cast object of type 'System.Collections.Generic.List`1' to type 'System.Collections.Generic.List`1'." ...
3
2584
by: Dave Booker | last post by:
Am I missing something here? It looks like the generic Queue<T> implements Enumerable<T> and ICollection but not ICollection<T>. (I want to use it in an interface that wants an ICollection<T>.) Is there a reason for this, or is it just an oversight in .NET 2.0? Is there a computationally easy way to cast/convert a Queue<T> to an ICollection<T>?
27
4349
by: Noah Roberts | last post by:
What steps do people take to make sure that when dealing with C API callback functions that you do the appropriate reinterpret_cast<>? For instance, today I ran into a situation in which the wrong type was the target of a cast. Of course with a reinterpret_cast nothing complains until the UB bites you in the ass. It seems to me that there ought to be a way to deal with these kinds of functions yet still retain some semblance of type...
9
7907
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private List<as a property. Consider the example below, the class "ListTest" contains a private "List<>" called "strings" - it also provides a public method to add to that list,
2
6168
by: Fred Mellender | last post by:
I am trying to use reflection to output the fields (names and values) of an arbitrary object -- an object dump to a TreeView. It works pretty well, but I am having trouble with generic lists, like List<char>. What I have working is : Type type = newObj.GetType(); //newObj is what I'm trying to dump
0
163
by: Pavel Minaev | last post by:
On Jul 24, 3:37 am, Alphapage <Alphap...@discussions.microsoft.com> wrote: Why, of course you can: public void Process<T>(IFoo<Tfoo) { ... }
4
1189
by: =?Utf-8?B?QWxwaGFwYWdl?= | last post by:
Hello again, My last question which opened a big debate about casting such a generic interface learned me a lot, but I can't find a way because of my particular generic interface. I will shown you my code, but when you will answer my post, don't write: - he is stupid (I already know) - this is not Object Oriented - generic is not made for that ...
0
9487
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9297
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9735
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8736
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7285
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6556
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5168
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.