473,385 Members | 1,769 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,385 software developers and data experts.

Inheritance and Interfaces

GSL
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.
Nov 17 '05 #1
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!

Nov 17 '05 #2
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.
-------
Regards ,
C#, VB.NET , SQL SERVER , UML , DESIGN Patterns Interview question book
http://www.geocities.com/dotnetinterviews/
My Interview Blog
http://spaces.msn.com/members/dotnetinterviews/

Nov 17 '05 #3
"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.
Nov 17 '05 #4
> 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.
Nov 17 '05 #5
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.

Nov 17 '05 #6
GSL
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.

Nov 17 '05 #7
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
Nov 17 '05 #8
SP
"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
Nov 17 '05 #9

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

Similar topics

3
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
8
by: Shawn Casey | last post by:
Consider the following code: interface IBase { virtual void BaseFunction() = 0; }; interface IDerived : public IBase { virtual void DerivedFunction() = 0;
12
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...
22
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...
15
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...
7
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...
0
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...
23
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; };
18
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...
3
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,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
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,...
0
Oralloy
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,...
0
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...

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.