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

downcasting... can't do it but...

Hi Folks,

I've accepted that one cannot downcast between types, however I can't find a
way to achieve

//...

class Employee
{
public string name;
}

class ContractEmployee : Employee
{
public string contractID;
}

class SomeOtherKindofEmployee : Employee
{
public string relevantAttribute;
}

class SampleProgram
{

public static void Main()
{
//we need to create the employee object and work with it
Employee e = new Employee();
e.name = "Fred";
//later, we need to specify the Employee as a ContractEmployee
// but the operation will fail because it is a down-level cast.
ContractEmployee c = (ContractEmployee) e;
c.contractID = "1234";
}
}

//...

How else would I create the 'ContractEmployee' object without having to
explicity copy the value's from all of the Employee object's properties to
the newly created ContractEmployee object's properties? I mean, it seems to
me that the 'ContractEmployee' object is just an extension of the 'Employee'
object so why cant I just add properties to an object by changing it's type
to a downlevel (child) type?

Rein
Nov 15 '05 #1
6 1894

In order to downcast from Employee to ContractEmployee you
must be working with an instance of ContractEmployee. In
your code snippet you instantiated an "Employee" --> and
that is what you've got. This code will work on the first
call to "SomeMethod()" but it will fail on the second:

ContractEmployee ce = new ContractEmployee();
Employee e = new Employee();

SomeMethod(ce);
SomeMethod(e);
SomeMethod(Employee e)
{
ContractEmployee ce = (ContractEmployee) e;
}
In order to do what you want you need to add a constructor
form or a "Convert" method to ContractEmployee and
SomeOtherKindOfEmployee that takes an Employee as an
argument and then manually converts to the new type...

--Richard

-----Original Message-----
Hi Folks,

I've accepted that one cannot downcast between types, however I can't find away to achieve

//...

class Employee
{
public string name;
}

class ContractEmployee : Employee
{
public string contractID;
}

class SomeOtherKindofEmployee : Employee
{
public string relevantAttribute;
}

class SampleProgram
{

public static void Main()
{
//we need to create the employee object and work with it Employee e = new Employee();
e.name = "Fred";
//later, we need to specify the Employee as a ContractEmployee // but the operation will fail because it is a down- level cast. ContractEmployee c = (ContractEmployee) e;
c.contractID = "1234";
}
}

//...

How else would I create the 'ContractEmployee' object without having toexplicity copy the value's from all of the Employee object's properties tothe newly created ContractEmployee object's properties? I mean, it seems tome that the 'ContractEmployee' object is just an extension of the 'Employee'object so why cant I just add properties to an object by changing it's typeto a downlevel (child) type?

Rein
.

Nov 15 '05 #2
Thanks Richard,

This is what I had suspected but had hoped I might avoid. It occurs to me
that a downlevel cast *should* be allowed in cases of inheritance - just as
a sensible convenience. So " ContractEmployee ce = (ContractEmployee) e; "
would simply provide ce with it's inherited attributes - similar to boxing.
That's the whole idea of inheritance isn't it? To normalize the data by
generalizing...

To put it another way, if through inheritance, we can say a ContractEmployee
*is* an Employee, then why can't I perform this downlevel cast?

There must be a good reason but I'm not familiar with it...

Rein

"Richard" <ri******@amgen.com> wrote in message
news:0e****************************@phx.gbl...

In order to downcast from Employee to ContractEmployee you
must be working with an instance of ContractEmployee. In
your code snippet you instantiated an "Employee" --> and
that is what you've got. This code will work on the first
call to "SomeMethod()" but it will fail on the second:

ContractEmployee ce = new ContractEmployee();
Employee e = new Employee();

SomeMethod(ce);
SomeMethod(e);
SomeMethod(Employee e)
{
ContractEmployee ce = (ContractEmployee) e;
}
In order to do what you want you need to add a constructor
form or a "Convert" method to ContractEmployee and
SomeOtherKindOfEmployee that takes an Employee as an
argument and then manually converts to the new type...

--Richard

-----Original Message-----
Hi Folks,

I've accepted that one cannot downcast between types,

however I can't find a
way to achieve

//...

class Employee
{
public string name;
}

class ContractEmployee : Employee
{
public string contractID;
}

class SomeOtherKindofEmployee : Employee
{
public string relevantAttribute;
}

class SampleProgram
{

public static void Main()
{
//we need to create the employee object and work

with it
Employee e = new Employee();
e.name = "Fred";
//later, we need to specify the Employee as a

ContractEmployee
// but the operation will fail because it is a down-

level cast.
ContractEmployee c = (ContractEmployee) e;
c.contractID = "1234";
}
}

//...

How else would I create the 'ContractEmployee' object

without having to
explicity copy the value's from all of the Employee

object's properties to
the newly created ContractEmployee object's properties? I

mean, it seems to
me that the 'ContractEmployee' object is just an

extension of the 'Employee'
object so why cant I just add properties to an object by

changing it's type
to a downlevel (child) type?

Rein
.

Nov 15 '05 #3
Rein... The reason is that you are not creating a new object of class
contractemployee. Instead, you are simply creating a new reference of
type contractemployee. A subtle, but important point.

http://www.geocities.com/jeff_louie/OOP/oop6.htm

Chapter 6 "Objects Have Class, References Have Type"*

Well, you have arrived. If you have survived to this point, you are
beginning to realize both the power and complexity of programming
using objects and inheritance. Much of the confusion about references,
types, classes and objects is simplified by the following statement
"Objects have class, references have type." The more technically correct
version may be "Objects have class, reference variables have type." As
long as it is understood that reference variables "contain" references
to
objects, the former statement is a superior in its simplicity

Regards,
Jeff
To put it another way, if through inheritance, we can say a

ContractEmployee *is* an Employee, then why can't I perform this
downlevel cast?<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #4
Rein Petersen <rm********@bogus.hotmail.com> wrote:
This is what I had suspected but had hoped I might avoid. It occurs to me
that a downlevel cast *should* be allowed in cases of inheritance - just as
a sensible convenience. So " ContractEmployee ce = (ContractEmployee) e; "
would simply provide ce with it's inherited attributes - similar to boxing.
That's the whole idea of inheritance isn't it? To normalize the data by
generalizing...

To put it another way, if through inheritance, we can say a ContractEmployee
*is* an Employee, then why can't I perform this downlevel cast?
A ContractEmployee *is* an Employee, but not every Employee is a
ContractEmployee.
There must be a good reason but I'm not familiar with it...


Safety. You shouldn't use objects in a way that they weren't
constructed for. For instance, what would you expect the following code
to do?

object o = new object();
FileStream fs = (FileStream) o;
fs.Read();

That's just as valid as your trying to cast an Employee instance to a
ContractEmployee instance - in the latter case, the ContractEmployee
couldn't have a valid contract id, for a start.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
On Wed, 1 Oct 2003 18:06:32 -0400, "Rein Petersen"
<rm********@bogus.hotmail.com> wrote:
Thanks Richard,

This is what I had suspected but had hoped I might avoid. It occurs to me
that a downlevel cast *should* be allowed in cases of inheritance - just as
a sensible convenience. So " ContractEmployee ce = (ContractEmployee) e; "
would simply provide ce with it's inherited attributes - similar to boxing.
That's the whole idea of inheritance isn't it? To normalize the data by
generalizing...

To put it another way, if through inheritance, we can say a ContractEmployee
*is* an Employee, then why can't I perform this downlevel cast?

There must be a good reason but I'm not familiar with it...

<snip>
The reason is because you never created a ContractEmployee in the
first place. You created a vanilla Employee. If the compiler
permitted such a downcast, then you could refer to fields/methods/
properties via such a ContractEmployee reference that are not
present in the originally created object, because you just
created a simple Employee.

Oz
Nov 15 '05 #6
Consider this:

You instanced an employee object. That's what is actually in memory, and
memory was allocated just for that object.

Now, if this were allowed:
contractemployee ce = (contractemployee)e;
Where would the contractID property go? Memory was never allocated for it
because you actually asked for an employee.

Now, you can do the exact opposite of this
(this code is completely legal --unless I goofed up the syntax <g>):

Employee e = new ContractEmployee();

e.Name = "Fred";
ContractEmployee ce = (ContractEmployee)e; // this works because e really is
a ContractEmployee
ce.ContractId = "1234";

Now, you can allow some indirection by having a method that returns the
right kind of employee:

Employee e = EmployeeFactory.GetEmployee(); // Get employee figures out what
kind of employee to instance, in this case a ContractEmployee
if(e is ContractEmployee)
{
ContractEmployee ce = (ContractEmployee)e;
// etc
}
else if(e is SomeOtherKind)
{
}

(however, if you find yourself with a lot of code like this, it could mean
that there is a design problem).

-- or --
You could just use
ContractEmployee ce = (ContractEmployee)e; // exception will be thrown if e
is not a ContractEmployee
-- or--
you could use
ContractEmployee ce = (e as ContractEmployee); // if e is not really a
ContractEmployee, ce == null

"Rein Petersen" <rm********@bogus.hotmail.com> wrote in message
news:e8**************@TK2MSFTNGP10.phx.gbl...
Thanks Richard,

This is what I had suspected but had hoped I might avoid. It occurs to me
that a downlevel cast *should* be allowed in cases of inheritance - just as a sensible convenience. So " ContractEmployee ce = (ContractEmployee) e; "
would simply provide ce with it's inherited attributes - similar to boxing. That's the whole idea of inheritance isn't it? To normalize the data by
generalizing...

To put it another way, if through inheritance, we can say a ContractEmployee *is* an Employee, then why can't I perform this downlevel cast?

There must be a good reason but I'm not familiar with it...

Rein

"Richard" <ri******@amgen.com> wrote in message
news:0e****************************@phx.gbl...

In order to downcast from Employee to ContractEmployee you
must be working with an instance of ContractEmployee. In
your code snippet you instantiated an "Employee" --> and
that is what you've got. This code will work on the first
call to "SomeMethod()" but it will fail on the second:

ContractEmployee ce = new ContractEmployee();
Employee e = new Employee();

SomeMethod(ce);
SomeMethod(e);
SomeMethod(Employee e)
{
ContractEmployee ce = (ContractEmployee) e;
}
In order to do what you want you need to add a constructor
form or a "Convert" method to ContractEmployee and
SomeOtherKindOfEmployee that takes an Employee as an
argument and then manually converts to the new type...

--Richard

-----Original Message-----
Hi Folks,

I've accepted that one cannot downcast between types,

however I can't find a
way to achieve

//...

class Employee
{
public string name;
}

class ContractEmployee : Employee
{
public string contractID;
}

class SomeOtherKindofEmployee : Employee
{
public string relevantAttribute;
}

class SampleProgram
{

public static void Main()
{
//we need to create the employee object and work

with it
Employee e = new Employee();
e.name = "Fred";
//later, we need to specify the Employee as a

ContractEmployee
// but the operation will fail because it is a down-

level cast.
ContractEmployee c = (ContractEmployee) e;
c.contractID = "1234";
}
}

//...

How else would I create the 'ContractEmployee' object

without having to
explicity copy the value's from all of the Employee

object's properties to
the newly created ContractEmployee object's properties? I

mean, it seems to
me that the 'ContractEmployee' object is just an

extension of the 'Employee'
object so why cant I just add properties to an object by

changing it's type
to a downlevel (child) type?

Rein
.


Nov 15 '05 #7

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

Similar topics

6
by: Stuart Golodetz | last post by:
Hi, I've got a minor casting issue which I need to check about (marked // <--). I was trying to do a static_cast on it (which didn't work, though I'm not sure why this should be the case?) I...
9
by: Simon Elliott | last post by:
If I have a base class and several possible derived classes, and I have a pointer to the base class, what's the best way of determining whether the pointer is pointing to a base class or to a...
2
by: Michael | last post by:
Ok Guys, on the same thread I'm writing a Game engine, which performs collision detection. I want to sepate the collision boundings libaray from the main game engine and load it as a library....
0
by: Rein Petersen | last post by:
Hi Folks, I've accepted that one cannot downcast between types, however I can't find a way to achieve //... class Employee { public string name;
6
by: Fernando Rodríguez | last post by:
Hi, I have a class called UrlFetcher and keep several instances inside an ArrayList. This class has a fecth() method. When I iterate through the list calling the fetch() method, I have to...
3
by: Joe | last post by:
I know that I can upcast and /downcast in C#. Can it be done in VB.NET? I haven't seen any documentation on it. TIA, -- Joe VB.NET/C#/ASP.NET/ASP/VB/C++/Web and DB development/VBA...
2
by: Random | last post by:
I'm trying to find the method I need to explicitly cast a class to a type of one of the classes that inherits from it. I'm passing in the type of the class I want to cast to as a parameter of my...
5
by: Ryan van Roode | last post by:
Hello, An API function gives me an object of class 'Blah'. I have subclassed 'Blah' and added a few methods: class EnhancedBlah extends Blah { function enhancement1() {} function...
9
snowfall
by: snowfall | last post by:
What is downcasting and how to implement it?? Am not getting any tutorial on this... pls help...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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:
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...
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,...

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.