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

How to cast in c# (Just kidding). But I do have a non-trival casting question.

G'Day.

Anybodey got an idea on this problem.

Say I have a function object doCast(object obj, Type t);
It's job is to cast the obect (obj) to a new type (t) and return it.

Sounds so simple, but I cant seem to find a way to do it without some
prety extravigant hacks.

Can anybodey think of a simple solution that I am overlooking. (um for
..net 1.0)

-dm

Mar 17 '06 #1
16 1521
Opps there is a .net has a function that does this.....
Convert.ChangeType(...).

My bad.

-dm

Mar 17 '06 #2
<th*********@gmail.com> wrote:
Anybodey got an idea on this problem.

Say I have a function object doCast(object obj, Type t);
It's job is to cast the obect (obj) to a new type (t) and return it.

Sounds so simple, but I cant seem to find a way to do it without some
prety extravigant hacks.

Can anybodey think of a simple solution that I am overlooking. (um for
.net 1.0)


Well, normal casting (leaving aside actual conversions) wouldn't do you
any good, because the method signature would still have to be "object".
Are you looking to perform the various implicit and explicit
conversions?

--
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
Mar 17 '06 #3
Convert.ChangeType performs convertion, not simple cast, and requires
the object to implement IConvertible interface. If you simply want to
cast, the doCast function would make no sense since it returns object
and you have to cast the return value again.
Sounds so simple, but I cant seem to find a way to do it without some
prety extravigant hacks

I am curious what are those hacks?

Mar 17 '06 #4
> G'Day.

Anybodey got an idea on this problem.

Say I have a function object doCast(object obj, Type t); It's job is
to cast the obect (obj) to a new type (t) and return it.

Sounds so simple, but I cant seem to find a way to do it without some
prety extravigant hacks.

Can anybodey think of a simple solution that I am overlooking. (um for
.net 1.0)

-dm


What would be the difference from just doing:

SomeObject x;
SomeOtherObject y = (SomeOtherObject)x;

?

--
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2
Mar 17 '06 #5
Hi,

Say I have a function object doCast(object obj, Type t);
It's job is to cast the obect (obj) to a new type (t) and return it.

Sounds so simple, but I cant seem to find a way to do it without some
prety extravigant hacks.

Can anybodey think of a simple solution that I am overlooking. (um for
.net 1.0)


You will have to return an object reference, so I find the method itself
pretty useless as it's right now. What are you trying to do?


Mar 17 '06 #6
Hi,

What would be the difference from just doing:

SomeObject x;
SomeOtherObject y = (SomeOtherObject)x;


The OP do not have SomeOtherObject nor he knows what it's , all he has is a
Type instance representing it.
Mar 17 '06 #7
Hello again, I thought is had solved the problem but as pointed out by
Truong it only works for classes implementing IConvetable.

Basicly I need to convert an object to a new type where the "new type"
is determined at runtime.

I think this is actuly a challange now...

basicly complete this stub:
object doCast(object obj, Type t)
{
object obj;

///magic code goes here to conver obj to type t

return obj;
}

The person with the most elegant solution will win.... "New Zealand".
Dont miss your chance to own your own pacific island nation!

-dm

Mar 22 '06 #8
opps (bad stub, lets correct),

object doCast(object obj, Type t)
{
object newObj;

///magic code goes here to conver obj to type t

return newObj;
}
Idealy this would work....

newObj = obj as t;

-dm

Mar 22 '06 #9
<th*********@gmail.com> wrote:
Hello again, I thought is had solved the problem but as pointed out by
Truong it only works for classes implementing IConvetable.

Basicly I need to convert an object to a new type where the "new type"
is determined at runtime.


Well, how do you expect that conversion to happen? What has the
knowledge to convert one type to another in your code?

For instance, suppose I have two classes:

FirstClass
{
int x;
}

SecondClass
{
string y;
}

How would you expect it to convert an instance of FirstClass into an
instance of SecondClass?

--
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
Mar 22 '06 #10
RE: How would you expect it to convert an instance of FirstClass into
an
instance of SecondClass?

In the usual way.....

If SecondClass or FirstClass have an appropriate cast operator than
that operator is used.

Otherwise invalidcastexception would be thrown.
-dm

Mar 24 '06 #11
This of couse makes one think of using getmethodinfo to retrive the
valid cast operattor and then invokeing it.... I just don't like messy
solutions to simple problems.

I could also emit my own code with the corect cast in it, again so very
messy...

There must be an easier way. Its such a simple problem.

-dm

Mar 24 '06 #12

<th*********@gmail.com> wrote in message
news:11*********************@g10g2000cwb.googlegro ups.com...
RE: How would you expect it to convert an instance of FirstClass into
an
instance of SecondClass?

In the usual way.....

If SecondClass or FirstClass have an appropriate cast operator than
that operator is used.

Otherwise invalidcastexception would be thrown.


Hi,

You keep using the terms CAST and CONVERT interchangeably.
They do not mean the same thing.

You convert an object into a different object based on some conversion rules.
There are 2 different objects involved
The original object
The converted object

When you cast an object to a different type there is only 1 object involved
Animal animal = new Dog();
Dog dog = (Dog)animal;

There is only one object in the above snippet, and both animal and dog reference it.

So,.....Are you attempting to Cast or Convert in your question?

Bill


Mar 24 '06 #13
I mean to say Cast as in the calling the cast operator (if it exists).

object doCast(object obj, Type t)
{
object newObj;

///magic code goes here to CAST obj to type t and assign it to
newObj

return newObj;
}

class dog
{
string name;
public static explicit operator carnivourusAnimal(dog d)
{
return new carnviourusAnimal(d.name, "beef roo mutton", "woof bark
howl");
}
}

//example useage
object dog = new dog();
Type streamAs = typeof(carnivourusAnimal);

if (protocol.ExplicitTypeRequired)
streamAs = protocol.TypeRequired;

object StreamObject = doCast(dingo, streamAs);
sendItem(StreamObject);

Mar 24 '06 #14
<th*********@gmail.com> wrote in message
news:11*********************@i40g2000cwc.googlegro ups.com...
I mean to say Cast as in the calling the cast operator (if it exists).
You keep saying that.
But your example is that of an explicit conversion....not a cast.

To late to think straight right now.
I'll look at your example again tomorrow
Bill

object doCast(object obj, Type t)
{
object newObj;

///magic code goes here to CAST obj to type t and assign it to
newObj

return newObj;
}

class dog
{
string name;
public static explicit operator carnivourusAnimal(dog d)
{
return new carnviourusAnimal(d.name, "beef roo mutton", "woof bark
howl");
}
}

//example useage
object dog = new dog();
Type streamAs = typeof(carnivourusAnimal);

if (protocol.ExplicitTypeRequired)
streamAs = protocol.TypeRequired;

object StreamObject = doCast(dingo, streamAs);
sendItem(StreamObject);

Mar 24 '06 #15
Thanks,

I guess we dont' exactly use the same lingo...

Lets define a term "transformation" (what I want)
The "transformation" is the act of calling:
implicit or explicit numeric conversions
implicit or explicit User-defined conversions.

This does not cover base class generalistaion (non-user-defined cast to
a parent type or to an implemented interface). The reason being that
the object is already of that type and hence our function would be of
no benifit. Notice that in my example dog did not derive from
carnivourusAnimal. If dog had derived from carnivourusAnimal then there
would be no poing in doing the cast sice the dog would already be a
carnivourusAnimal.

when the doCast function is called a serach is conducted for a suitable
"transformation" and that transformation is applied.

This is probably most usefull in situations where a comunications class
species a type which it expects to recive information in.

Basicly what I want is a way for objects "product" to be shaped into a
type that may be required by another process "consumer". The process
does not need to be altered to accomidate new classes that apear. The
process needs only to provide information on what type it requires.

The "item" class then only needs a suitable user-defined conversion and
its intergration into the application is done.

This is only usefull if new "item" classss are often indroduced into
the aplication and the what the "consumer" wants is determined at
runtime, and what the consumer expects can not be generalised to a base
class or common interface.

-dm

Mar 24 '06 #16
<th*********@gmail.com> wrote in message
news:11*********************@i40g2000cwc.googlegro ups.com...
Thanks,

I guess we dont' exactly use the same lingo...

Lets define a term "transformation" (what I want)
The "transformation" is the act of calling:
implicit or explicit numeric conversions
implicit or explicit User-defined conversions.
Fair enough, Transformation works fine
This does not cover base class generalistaion (non-user-defined cast to
a parent type or to an implemented interface). The reason being that
the object is already of that type and hence our function would be of
no benifit. Notice that in my example dog did not derive from
carnivourusAnimal. If dog had derived from carnivourusAnimal then there
would be no poing in doing the cast sice the dog would already be a
carnivourusAnimal.
I believe that this was the source of some confusion in some of the responses.
when the doCast function is called a serach is conducted for a suitable
"transformation" and that transformation is applied.

This is probably most usefull in situations where a comunications class
species a type which it expects to recive information in.

Basicly what I want is a way for objects "product" to be shaped into a
type that may be required by another process "consumer". The process
does not need to be altered to accomidate new classes that apear. The
process needs only to provide information on what type it requires.

The "item" class then only needs a suitable user-defined conversion and
its intergration into the application is done.
OK, I am confused again.
Is an "item" class different from a "product" class, or have we changed names????
This is only usefull if new "item" classss are often indroduced into
the aplication and the what the "consumer" wants is determined at
runtime, and what the consumer expects can not be generalised to a base
class or common interface.


OK,
I think the problem most of us are having is that you are asking for a general object to object
transform method/class. However, in general, most objects SHOULD NOT be convertible into any old
object. Don't get me wrong, You COULD write a general object transformer, but most of the cases
would need to throw some "Untransformable" Exception. And in general, the results would not be
pretty.
Of cause looking at your product/item/consumer description, it doesn't look like you really need
a generic transformer at all. So the real question is, "What do you really need?"

So let me ask a few questions, to narrow down the scope a bit.
Are we talking about external vendors? Web services? In house services? Are they separate processes
or just separate threads?
How many consumers are we talking about? Do they do the same thing, or different things?
Will CONSUMER_A always want the same type, or will it vary from call to call?

Is each product a different class?
Is there a common ancestor?

Is there a 1- to -1 mapping of objects from your side to the "consumer" side?
ProductA -->Consumer1ProductA
ProductA -->Consumer2ProductA
ProductB -->Consumer1ProductB
ProductB -->Consumer2ProductB

Or is more like this
ProductA -->Consumer1Product
ProductA -->Consumer2Product
ProductB -->Consumer1Product
ProductB -->Consumer2Product

Or is it something more complex?

I guess the bottom line is that depending on the problem you are attempting to solve, the best
solution may look quite different. However, I am fairly certain that a generic "Transformer" is
probably not the ideal solution. I am not saying that you don't need a means of converting types, I
am simply saying that it would be better to narrow down the scope to something smaller that
"anything to anything else".

Bill





Mar 27 '06 #17

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

Similar topics

3
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? ...
5
by: Basil | last post by:
Hello. Compiler BCB60. There is a simple example: class a1 { int v; public: a1 ():v (0) {} a1 (int v1):v (v1) {}
5
by: Luke Dalessandro | last post by:
Code: Thread -> U -> T public class Thread { protected: thread_t _tid; virtual void foo() = 0; public: // Static entry function for the internal thread
36
by: MSG | last post by:
The answer is neither. Use macros. #define ALLOC(size, type) ((type) *) malloc((size) * sizeof(type)) #define NEW(type, name, size) (type) * (name) = ALLOC((size), (type)) They are both ...
16
by: Amarendra GODBOLE | last post by:
Hi, I am a bit confused over the correct usage of memcpy(). Kindly help me clear the confusion. The linux manpage for memcpy(3) gives me the following prototype of memcpy(3): #include...
16
by: Martin Jørgensen | last post by:
Hi, Short question: Any particular reason for why I'm getting a warning here: (cast from function call of type int to non-matching type double) xdouble = (double)rand()/(double)RAND_MAX;
9
by: Frederick Gotham | last post by:
Let's assume that we're working on the following system: CHAR_BIT == 8 sizeof( char* ) == 4 (i.e. 32-Bit) Furthermore, lets assume that the memory addresses are distributed as follows: ...
6
by: Jack | last post by:
Is it possible to cast a 4-byte data type (e.g. an unsigned int) to a 4-byte struct? Sometimes the HIWORD and LOWORD of a 4-byte value contain information independent of each other. Is there a...
10
by: mypetrock | last post by:
Has anyone run into this error message? Unable to cast object of type 'Foo.Bar' to type 'Foo.Bar'. I'm trying to cast an object of type Foo.Bar that I got out of a hash table into a variable...
15
by: Lloyd Dupont | last post by:
Don't mistake generic type for what you would like them to be!! IFoo<Ahas nothing in common with IFoo<B>! They are completely different type create dynamically at runtime. What you ask is a...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
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: 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 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.