I need help understanding why the following code causes an
InvalidCastException?
//I created an Interface
public interface IFoo
{
string a {get;}
}
//Then a class that implements the interface
public class Foo: IFoo
{
string a {get "something";}
}
//Then a special class that derives from Foo and adds additional methods
public class MyFoo: Foo
{
string b {get "something else";}
}
Why does the following line of code not work?
IFoo foo = new Foo();
MyFoo myFoo = (MyFoo)foo; // <- InvalidCastException!
Thanks. 8 1496
GSL,
Basically because a Foo is not a MyFoo (Foo does not inherit from MyFoo).
Therefore, trying to cast a Foo to a MyFoo will result in an
InvalidCastException.
Note however, that a MyFoo is a Foo (MyFoo inherits from Foo). Therefore,
one can cast a MyFoo to a Foo without throwing an InvalidCastException.
Regards,
Randy I need help understanding why the following code causes an InvalidCastException?
//I created an Interface public interface IFoo { string a {get;} } //Then a class that implements the interface public class Foo: IFoo { string a {get "something";} } //Then a special class that derives from Foo and adds additional methods public class MyFoo: Foo { string b {get "something else";} }
Why does the following line of code not work? IFoo foo = new Foo(); MyFoo myFoo = (MyFoo)foo; // <- InvalidCastException!
"sh**********@yahoo.com" wrote: Because they do not implement the same interface. If your Myfoo also implements Ifoo then you can do that. I like the Foo examples.... they are all over the places for beginners.
The base class implements the interface so the derived class does to.
In any case, the interface is not relevent here.
> IFoo foo = new Foo(); MyFoo myFoo = (MyFoo)foo; // <- InvalidCastException!
The interface is not the problem here. The existence of the interface makes
the example more complicated so it is harder to see what is going on.
The problem is that the object is a Foo since you said "new Foo()". Casting
does not magically change an object from one type to another. You created a
Foo and it will be a Foo for its entire life.
The cast asks the runtime to give you a MyFoo reference to the Foo object.
Since the object is not in fact a MyFoo, the cast fails.
I created a collection class (FooCollection), which is the base class for
specialty collections (MyFooCollection). When I add a new object to the
specialty collection (base.Add()) I'd like the result to be a MyFoo, not a
Foo. So, I tried to create an Interface IFoo, thinking that if the base
class returned the Interface I could cast it to a MyFoo, which is a special
version of Foo. I'm trying to find a way to do this where I don't have to
re-write all of the code for Foo class in each MyFoo, because MyFoo just
extends the base class it doesn't hide anything.
What is the right way of doing this?
Thanks for the help.
"MarkT [developmentor]" <Ma****************@discussions.microsoft.com> wrote
in message news:8C**********************************@microsof t.com... IFoo foo = new Foo(); MyFoo myFoo = (MyFoo)foo; // <- InvalidCastException! The interface is not the problem here. The existence of the interface
makes the example more complicated so it is harder to see what is going on.
The problem is that the object is a Foo since you said "new Foo()".
Casting does not magically change an object from one type to another. You created
a Foo and it will be a Foo for its entire life.
The cast asks the runtime to give you a MyFoo reference to the Foo object. Since the object is not in fact a MyFoo, the cast fails.
I created a collection class (FooCollection), which is the base class for
specialty collections (MyFooCollection). When I add a new object to the
specialty collection (base.Add()) I'd like the result to be a MyFoo, not a
Foo. So, I tried to create an Interface IFoo, thinking that if the base
class returned the Interface I could cast it to a MyFoo, which is a special
version of Foo. I'm trying to find a way to do this where I don't have to
re-write all of the code for Foo class in each MyFoo, because MyFoo just
extends the base class it doesn't hide anything.
What is the right way of doing this?
Thanks for the help.
"MarkT [developmentor]" <Ma****************@discussions.microsoft.com> wrote
in message news:8C**********************************@microsof t.com... IFoo foo = new Foo(); MyFoo myFoo = (MyFoo)foo; // <- InvalidCastException! The interface is not the problem here. The existence of the interface
makes the example more complicated so it is harder to see what is going on.
The problem is that the object is a Foo since you said "new Foo()".
Casting does not magically change an object from one type to another. You created
a Foo and it will be a Foo for its entire life.
The cast asks the runtime to give you a MyFoo reference to the Foo object. Since the object is not in fact a MyFoo, the cast fails.
Peter <pe***@latsos.com> wrote: I created a collection class (FooCollection), which is the base class for specialty collections (MyFooCollection). When I add a new object to the specialty collection (base.Add()) I'd like the result to be a MyFoo, not a Foo.
What kind of object are you adding though?
So, I tried to create an Interface IFoo, thinking that if the base class returned the Interface I could cast it to a MyFoo, which is a special version of Foo.
You can only cast it if it *is* a MyFoo, or if there's a conversion
defined between the declared type and MyFoo.
I'm trying to find a way to do this where I don't have to re-write all of the code for Foo class in each MyFoo, because MyFoo just extends the base class it doesn't hide anything.
What is the right way of doing this?
It's hard to say without knowing more about the real life situation, to
be honest. It may well be that the best way isn't to use inheritance at
all, for instance, but to use composition instead.
--
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
"GSL" <Gu***********@gmail.com> wrote in message
news:eY********************@comcast.com... I created a collection class (FooCollection), which is the base class for specialty collections (MyFooCollection). When I add a new object to the specialty collection (base.Add()) I'd like the result to be a MyFoo, not a Foo. So, I tried to create an Interface IFoo, thinking that if the base class returned the Interface I could cast it to a MyFoo, which is a special version of Foo. I'm trying to find a way to do this where I don't have to re-write all of the code for Foo class in each MyFoo, because MyFoo just extends the base class it doesn't hide anything.
What is the right way of doing this?
You can add any class that derives from Foo to your FooCollection. However
you will need to cast it back to the correct MyFoo. When I do this I have an
indexer that returns the derived type or null if it is not of that type.
public MyFoo MyFoo[int index]
{
get
if(this.InnerList[index] isMyFoo)
return (MyFoo)this.InnerList[index];
else
return null; ...
public MyOtherFoo MyOtherFoo[int index]
{
get
if(this.InnerList[index] isMyOtherFoo)
return (MyOtherFoo)this.InnerList[index];
else
return null;
SP This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Joe Delphi |
last post by:
Does Visual Basic support multiple inheritance? That is one child
class inheriting from more than one parent class.
JD
|
by: Shawn Casey |
last post by:
Consider the following code:
interface IBase
{
virtual void BaseFunction() = 0;
};
interface IDerived : public IBase
{
virtual void DerivedFunction() = 0;
|
by: Steve Jorgensen |
last post by:
The classing Visual Basic and VBA support for polymorphism, let's face it, is
a bit on the weak side, and built-in support for inheritance is non-existent.
This little essay is about some patterns...
|
by: Matthew Louden |
last post by:
I want to know why C# doesnt support multiple inheritance? But why we can
inherit multiple interfaces instead? I know this is the rule, but I dont
understand why. Can anyone give me some concrete...
|
by: Sinex |
last post by:
Hi,
Why does C# disallow multiple inheritance? Whats the reason behind this?
Is there any advantage or is it just a method to avoid some problems (if so,
what problems?) that come with multiple...
|
by: Hazz |
last post by:
Are there any good references/articles/books which provide clarity toward my
insecurity still on deciding how to model a complex system? I still feel
uncomfortable with my understanding, even...
|
by: Terry Hancock |
last post by:
I've been discussing PyProtocols with a a friend
collaborating with me on a SF game project, about
the benefits and design concept of "component architecture",
and I'm a little confused by what...
|
by: Dave Rahardja |
last post by:
Since C++ is missing the "interface" concept present in Java, I've been using
the following pattern to simulate its behavior:
class Interface0
{
public:
virtual void fn0() = 0;
};
|
by: GD |
last post by:
Please remove ability to multiple inheritance in Python 3000.
Multiple inheritance is bad for design, rarely used and contains many
problems for usual users.
Every program can be designed only...
|
by: johanatan |
last post by:
When I first heard about these new features, I was very excited as it
would have (if implemented as I had expected) rendered mimicking
multiple inheritance almost painless in C#. Unfortunately,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
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...
| |