issue type casting derived object to base object

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

I have the following objects and namespaces

namespace MyNameSpace.Borrowers
{
public class Borrower()
{

}
}


namespace MyNameSpace.NewSystem.Borrowers
{
public class Borrower() : MyNameSpace.Borrowers.Borrower
{

}
}


Now I have the following code:

MyNameSpace.NewSystem.Borrowers.Borrower derivedObject = some value...

MyNameSpace.Borrowers.Borrower baseObject = (derivedObject as
MyNameSpace.Borrowers.Borrower)


I am getting an issue because the variable baseObject still points to an
instance of MyNameSpace.NewSystem.Borrowers.Borrower instead of
MyNameSpace.Borrowers.Borrower.

Am I missing something? Any ideas?

TIA!
 
MyNameSpace.NewSystem.Borrowers.Borrower derivedObject = some value...
MyNameSpace.Borrowers.Borrower baseObject = (derivedObject as
MyNameSpace.Borrowers.Borrower)

A cast shouldn't be required. The compiler can figure out that a
direct assignment is valid by looking at the inheritance hierarchy.

I am getting an issue because the variable baseObject still points to an
instance of MyNameSpace.NewSystem.Borrowers.Borrower instead of
MyNameSpace.Borrowers.Borrower.

Am I missing something? Any ideas?

What kind of "issue"? Casting doesn't change the type of the object,
only which subset of its members you have access to.


Mattias
 
Now I have the following code:

MyNameSpace.NewSystem.Borrowers.Borrower derivedObject = some value...

MyNameSpace.Borrowers.Borrower baseObject = (derivedObject as
MyNameSpace.Borrowers.Borrower)


I am getting an issue because the variable baseObject still points to an
instance of MyNameSpace.NewSystem.Borrowers.Borrower instead of
MyNameSpace.Borrowers.Borrower.

Am I missing something? Any ideas?

Well, for a start you should *really* try not to use the same class
name in multiple places, particularly not in the same inheritance
hierarchy. That's a recipe for confusion.

Now, as for your question: casting and using "as" don't change the type
of the object. They just let you cast down so that when you know more
than the compiler (e.g. "I know that variable x is of type object, but
actually the value is a reference to a string") you can give that
information.

You can't change the actual type of an object.
 
Back
Top