472,374 Members | 1,309 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,374 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 1465
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...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.
0
DizelArs
by: DizelArs | last post by:
Hi all) Faced with a problem, element.click() event doesn't work in Safari browser. Tried various tricks like emulating touch event through a function: let clickEvent = new Event('click', {...

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.