Question Locked

Casting an object to a type that the object inherits from - C#

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have a C# object of type _BaseFormDataEntry.
I also have a C# object that inherits from the the _BaseFormDataEntry object called FormDetailSearch.
i have a property that returns a _BaseFormDataEntry typed object.
in that property the return value is of _BaseFormDataEntry type and i would like to cast the object FormDetailSearch (which inherits from _BaseFormDataEntry) into and object of type _BaseFormDataEntry.

does this type of conversion make sense? if not, what would be the correct way?

as it is right now the property throws and exception when it tries to perform the cast and basically says it cannot cast the object FormDetailSearch into object of type _BaseFormDataEntry. what's am i doing wrong?

5 replies

by smyers

What you are doing seems correct, how are you doing the cast, like so?
FormDetailSearch fds = otherObject.myProperty;
_BaseFormDataEntry bfde = (_BaseFormDataEntry)fds;

by bnemec

my code is exactly that. the code works great at runtime, no exceptions or anything. it's just the designer that throws an exception in vs2005.

by lyletaylor

It is not necessary to cast a subclass to the superclass when assigning it to a variable of the superclass's type. It's only necessary to use a cast when you have a variable of the superclass's type and you want to use it as the subclass.

For example, if you have two classes A and B where B inherits from A, you would have the following:

B bvar = new B();
A avar = bvar; // no cast necessary because B contains everything represented by A.
B bvar2 = (B) avar; // cast necessary because B is more specific that A.

However, if I understand your original post correctly, and otherObject returns a _BaseFormDataEntry object, the code posted by smyers would be incorrect. A cast would be required in the first line, but not the second:

FormDetailSearch fds = (FormDetailsSearch) otherObject.myProperty;
_BaseFormDataEntry bfde = fds; // No cast necessary since FDS inherits from BFDE

by bnemec

i'll have to test that out...i'm onto another project so i gotta put this one aside for now, thanks for the help though...

This discussion is closed to new replies.