473,770 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic Casting

Hi,

I have a need for "dynamic type casting": in other words, in a "MyConvert"
method I get passed an Object "value" and a Type "type" and the method
should attempt to convert value into type.

Of course it first tries to obtain the appropriate TypeConverter. However,
for some types there are no applicable type converters.
Consider a custom class "Dummy" from a linked assembly (in my scenario,
neither the Dummy type nor its assembly are "known", meaning any Type from
any assembly could be passed). There is no TypeConverter associated with
Dummy, however, it defines implicit cast operators to convert between Dummy
and String. I would like to know whether there is a standard way of
performing such a "dynamic" or "runtime" cast. I tried Convert.ChangeT ype()
but that method only works with IConvertible types---and completely ignores
any cast operators defined on any of the two types (that of value, and the
target Type).

Any ideas?
Many thanks,
Phil
Nov 17 '05 #1
6 6407
I gather there is no built-in way to do this?...

"Philipp Schumann" <ph**@mokka.org > schrieb im Newsbeitrag
news:uP******** ******@TK2MSFTN GP14.phx.gbl...
Hi,

I have a need for "dynamic type casting": in other words, in a "MyConvert"
method I get passed an Object "value" and a Type "type" and the method
should attempt to convert value into type.

Of course it first tries to obtain the appropriate TypeConverter. However,
for some types there are no applicable type converters.
Consider a custom class "Dummy" from a linked assembly (in my scenario,
neither the Dummy type nor its assembly are "known", meaning any Type from
any assembly could be passed). There is no TypeConverter associated with
Dummy, however, it defines implicit cast operators to convert between
Dummy and String. I would like to know whether there is a standard way of
performing such a "dynamic" or "runtime" cast. I tried
Convert.ChangeT ype() but that method only works with IConvertible
types---and completely ignores any cast operators defined on any of the
two types (that of value, and the target Type).

Any ideas?
Many thanks,
Phil

Nov 17 '05 #2
Dan
How would the code following the cast know how to treat a reference
that it does not have type information for at compile time? I'm pretty
sure that there is no way to dynamically cast the way you want it to.
I have to do similar things to what you describe in my projects. I
have a manager that will call objects that were created well after the
manager was compiled. I have found that I can work around this issue
using interfaces/base classes and solve the problems in a more type
safe way. To convert your dummy class to a string the easiest way to
do what you want is override .ToString(). In that case you can use the
base class to provide the interface to provide the conversion.

If all of your dummy classes implement the same conversions, try
creating and implementing 1 or more interfaces like IToDecimal,
IToDateTime etc. It sucks that you cannot define operators in an
interface, but you can do the same work with methods and properties
(though not as pretty)

HTH,
Dan

Nov 17 '05 #3
You don't need a dynamic cast. You need to fix your design....
[class Dummy] defines implicit cast operators to convert between Dummy
and String.

implicit cast operators? eek.. Replacement them with explicit
conversion functions, say ToString & FromString. Define an interface, have
Dummy (and your other classes) implement that interface.

interface IToFromString
{
string ToString();
void FromString(stri ng str);
}

public class Dummy : IToFromString
{
public override string ToString() {.... }
public void FromString(stri ng str) {.....}
}
ThatFunctionInA DifferentAssemb ly(IToFromStrin g obj)
{
Console.WriteLi ne(obj.ToString ());
}

--
--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Philipp Schumann" <ph**@mokka.org > wrote in message
news:uP******** ******@TK2MSFTN GP14.phx.gbl... Hi,

I have a need for "dynamic type casting": in other words, in a "MyConvert"
method I get passed an Object "value" and a Type "type" and the method
should attempt to convert value into type.

Of course it first tries to obtain the appropriate TypeConverter. However,
for some types there are no applicable type converters.
Consider a custom class "Dummy" from a linked assembly (in my scenario,
neither the Dummy type nor its assembly are "known", meaning any Type from
any assembly could be passed). There is no TypeConverter associated with
Dummy, however, it defines implicit cast operators to convert between Dummy and String. I would like to know whether there is a standard way of
performing such a "dynamic" or "runtime" cast. I tried Convert.ChangeT ype() but that method only works with IConvertible types---and completely ignores any cast operators defined on any of the two types (that of value, and the
target Type).

Any ideas?
Many thanks,
Phil

Nov 17 '05 #4
Who says it is my design? My design just wants to work with ANY scenario, so
whether or not I _personally_ prefer the convenience of cast operators
(which can mean a lot _less_ overload definitions for many functions)
doesn't matter here. That said, the Dummy class was a moniker for all the
unknown types the API will need to work with, rather than a smallish design
of my own which I can change as I (or you) wish...

The whole issue actually makes me wonder whether type conversions are C#
syntactic sugar rather than supported at the framework level. Almost
certainly seems to be the case, will have to check that.

"James Curran" <ja*********@mv ps.org> schrieb im Newsbeitrag
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
You don't need a dynamic cast. You need to fix your design....
[class Dummy] defines implicit cast operators to convert between Dummy

and String.

implicit cast operators? eek.. Replacement them with explicit
conversion functions, say ToString & FromString. Define an interface,
have
Dummy (and your other classes) implement that interface.

interface IToFromString
{
string ToString();
void FromString(stri ng str);
}

public class Dummy : IToFromString
{
public override string ToString() {.... }
public void FromString(stri ng str) {.....}
}
ThatFunctionInA DifferentAssemb ly(IToFromStrin g obj)
{
Console.WriteLi ne(obj.ToString ());
}

--
--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Philipp Schumann" <ph**@mokka.org > wrote in message
news:uP******** ******@TK2MSFTN GP14.phx.gbl...
Hi,

I have a need for "dynamic type casting": in other words, in a
"MyConvert"
method I get passed an Object "value" and a Type "type" and the method
should attempt to convert value into type.

Of course it first tries to obtain the appropriate TypeConverter.
However,
for some types there are no applicable type converters.
Consider a custom class "Dummy" from a linked assembly (in my scenario,
neither the Dummy type nor its assembly are "known", meaning any Type
from
any assembly could be passed). There is no TypeConverter associated with
Dummy, however, it defines implicit cast operators to convert between

Dummy
and String. I would like to know whether there is a standard way of
performing such a "dynamic" or "runtime" cast. I tried

Convert.ChangeT ype()
but that method only works with IConvertible types---and completely

ignores
any cast operators defined on any of the two types (that of value, and
the
target Type).

Any ideas?
Many thanks,
Phil


Nov 17 '05 #5
Who says it is my design? My design just wants to work with ANY scenario, so
whether or not I _personally_ prefer the convenience of cast operators
(which can mean a lot _less_ overload definitions for many functions)
doesn't matter here. That said, the Dummy class was a moniker for all the
unknown types the API will need to work with, rather than a smallish design
of my own which I can change as I (or you) wish...

The whole issue actually makes me wonder whether type conversions are C#
syntactic sugar rather than supported at the framework level. Almost
certainly seems to be the case, will have to check that.

"James Curran" <ja*********@mv ps.org> schrieb im Newsbeitrag
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
You don't need a dynamic cast. You need to fix your design....
[class Dummy] defines implicit cast operators to convert between Dummy

and String.

implicit cast operators? eek.. Replacement them with explicit
conversion functions, say ToString & FromString. Define an interface,
have
Dummy (and your other classes) implement that interface.

interface IToFromString
{
string ToString();
void FromString(stri ng str);
}

public class Dummy : IToFromString
{
public override string ToString() {.... }
public void FromString(stri ng str) {.....}
}
ThatFunctionInA DifferentAssemb ly(IToFromStrin g obj)
{
Console.WriteLi ne(obj.ToString ());
}

--
--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Philipp Schumann" <ph**@mokka.org > wrote in message
news:uP******** ******@TK2MSFTN GP14.phx.gbl...
Hi,

I have a need for "dynamic type casting": in other words, in a
"MyConvert"
method I get passed an Object "value" and a Type "type" and the method
should attempt to convert value into type.

Of course it first tries to obtain the appropriate TypeConverter.
However,
for some types there are no applicable type converters.
Consider a custom class "Dummy" from a linked assembly (in my scenario,
neither the Dummy type nor its assembly are "known", meaning any Type
from
any assembly could be passed). There is no TypeConverter associated with
Dummy, however, it defines implicit cast operators to convert between

Dummy
and String. I would like to know whether there is a standard way of
performing such a "dynamic" or "runtime" cast. I tried

Convert.ChangeT ype()
but that method only works with IConvertible types---and completely

ignores
any cast operators defined on any of the two types (that of value, and
the
target Type).

Any ideas?
Many thanks,
Phil


Nov 17 '05 #6
Philipp Schumann <ph**@mokka.org > wrote:
Who says it is my design? My design just wants to work with ANY scenario, so
whether or not I _personally_ prefer the convenience of cast operators
(which can mean a lot _less_ overload definitions for many functions)
doesn't matter here. That said, the Dummy class was a moniker for all the
unknown types the API will need to work with, rather than a smallish design
of my own which I can change as I (or you) wish...

The whole issue actually makes me wonder whether type conversions are C#
syntactic sugar rather than supported at the framework level. Almost
certainly seems to be the case, will have to check that.


You can use reflection to find members with special names - they may
well help you. The operator is compiled into a method, just a special
one...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7

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

Similar topics

12
2186
by: Jason Tesser | last post by:
I work for at a college where I am one of 2 full-time developers and we are looking to program a new software package fro the campus. This is a huge project as it will include everything from registration to business office. We are considering useing Java or Python. I for one don't like Java because I feel the GUI is clunky. I also think that we could produce quality programs faster in Python.
5
8017
by: Radde | last post by:
HI, Are ther any pitfalls for dynamic cast in type safe downcasting..
2
2564
by: Zac | last post by:
Alright anyone who has 2c throw it in... I am working through a custom xml serializer and have come upon a conundrum, given our class design. The interface implemented on the base class (base for all business entities) dictates that the implementing class expose a Dirty property (for state). The base class (that actually manages state, once for all inheritors)
3
1950
by: Jeff Poste | last post by:
Hi, I'm developing software that requires business rules that constantly need new versions for different quarters, years, etc. I created a business rule factory that stores these different business rules in a hashtable indexed by the year, ie "3Q2003". Now based upon the key that I give the factory, it will return a reference to the correct business object for me to use. This works well as long as all of the business objects in the...
4
4963
by: Val | last post by:
Hi I am using a DynamicProxy (class that inherits from RealProxy). I don't know the type of my Transparant Proxy at compile time. Is there a possibility to have a dynamic casting object correctParams = new object for(int i... Type t = Type.GetType(tiB.GetTypeName()) DynamicProxy proxy = new DynamicProxy(t, orderedParams, tiA) correctParams = /*TODO: CAST into type t*/ proxy.GetTransparentProxy()
2
673
by: Martin Hart - Memory Soft, S.L. | last post by:
Hi all: I still very new to the .NET world and don't know if what I am asking is due to an over-imaginative imagination or the fact that I have read too many fiction books!! Let me show you a very basic scenario: using System;
4
2205
by: Zark3 | last post by:
Hi all, I was wondering if anybody could enlighten me on the possibility of dynamic casting. Or, well, whether or not I'm actually trying to do this the right way. What I have is a base class that several classes inherit from. From time to time I need to add new inherited types so I want something that is as versatile as possible, preferably not requiring naming all subtypes in a switch statement.
2
461
by: Mike Stevenson | last post by:
Hi. I'm in the process of re-learning all the C++ I forgot from college, and I'm starting to get into some virgin (or at least only a couple times) territory. I have some questions about casting a pointer from a base class to a derived class. For example: class Base{ public: Base() {} virtual ~Base() {} void func1(int);
28
6060
by: hlubenow | last post by:
Hello, I really like Perl and Python for their flexible lists like @a (Perl) and a (Python), where you can easily store lots of strings or even a whole text-file. Now I'm not a C-professional, just a hobby-programmer trying to teach it myself. I found C rather difficult without those lists (and corresponding string-functions). Slowly getting into C-strings, I thought, what if I take a C-string and
0
9617
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.