473,461 Members | 1,872 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Cast from name syntax

Hi all,

I am trying to cast a Double (its actually the NextDouble method of the
Random class, but could be any type of number) to a Type via its name.

Im trying the following syntax:

ThisNumber = (Type.GetType("MyType.Decimal"))(ThisRandom.NextDo uble());

Im getting an error stating that 'Method name expected', so either im
not casting correctly or using incorrect syntax?

Thanks,

Nick

Nov 17 '05 #1
6 1693
Nick,

when you use type casting using the syntax: "(<type>) obj" or "obj as
<type>", the <type> name has to be know during compilation. In other word
you can use (int)var, but cannot use (typeof(int))var or something like
that.

BTW in your code sample you do know the type you want to covert to it is
MyType.Decimal. Why don't you use

ThisNumber = (MyType.Decimal)(ThisRandom.NextDouble()); this will compile as
long as there is conversion between double and MyType.Decimal.

There is no general conversion from any type to any type. Usually there are
two types of dynamic conversion. One is when a type implements IConvertible
and the other is when a type has TypeConverter attached to it via an
attribute.

Since you want to convert from double to your own type IConvertible won't
work for you. Thus what you might wanna do is to create a TypeConverter for
your own type.

However, look again your design. I've found that in most of the cases when
programmers think that they don't know the type they want to convert to at
compile time, this is simply not the case. Look again the code you've
posted. I know that this is just a sample and the real world scenario could
be more complex.

Stoitcho Goutsev (100) [C# MVP]

"Nick Weekes" <ni***********@yahoo.co.uk> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
Hi all,

I am trying to cast a Double (its actually the NextDouble method of the
Random class, but could be any type of number) to a Type via its name.

Im trying the following syntax:

ThisNumber = (Type.GetType("MyType.Decimal"))(ThisRandom.NextDo uble());

Im getting an error stating that 'Method name expected', so either im
not casting correctly or using incorrect syntax?

Thanks,

Nick

Nov 17 '05 #2
Stoitcho,

Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?

Cheers,

Nick

Nov 17 '05 #3
First the difference between casting and converting.

When you are casting, you are saying that you know object X is really of
type Y. You are in effect telling the complier that it is safe to assign
object X to variable Z. There is no change to the underlying object.

Y Z = (Y)X;

When you are converting, you are creating a new object that has the same
value as the old one, but is in a different format. For example, when making
an integer into a double.
Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?
You aren't really casting in the design sense because you cannot make that
promise. Besides, when would you not know what type you wanted to cast to?

(You are still casting in the runtime sense. That is, the runtime is
verifying the cast is safe and the types are equivalent.)

--
Jonathan Allen
"Nick Weekes" <ni***********@yahoo.co.uk> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com... Stoitcho,

Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?

Cheers,

Nick

Nov 17 '05 #4
First the difference between casting and converting.

When you are casting, you are saying that you know object X is really of
type Y. You are in effect telling the complier that it is safe to assign
object X to variable Z. There is no change to the underlying object.

Y Z = (Y)X;

When you are converting, you are creating a new object that has the same
value as the old one, but is in a different format. For example, when making
an integer into a double.
Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?
You aren't really casting in the design sense because you cannot make that
promise. Besides, when would you not know what type you wanted to cast to?

(You are still casting in the runtime sense. That is, the runtime is
verifying the cast is safe and the types are equivalent.)

--
Jonathan Allen
"Nick Weekes" <ni***********@yahoo.co.uk> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com... Stoitcho,

Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?

Cheers,

Nick

Nov 17 '05 #5
This is just a language syntax, but I guess the reason is that the IL
instruction that this expression emits expects a type metadata token. It
cannot be generated at compile type if you use a variable that doesn't have
value at compile time. Keep in mind that the IL instruction for conversion
*castclass* converts only to/from classes and itnerfaces that are in
base/derived class relationship or the interface is implemented by the type.
All other convrsion techniques like IConvertible, TypeConverter or type
casting operators overloading (C#) is not taken into account. All such
conversions has to be done explicitly by the progeammer or the compiler.
They are not part of the .NET Runtime so to speak.

Dynamic conversion cannot be provided out of the box. The one who writes the
class only know how to convert it to/from another type. For example how
could the runtyme know how to cnonvert from string to Foo. Only me (the
programmer who wrote this foo class) knows how to do that and if this
conversion makes any sense after all. The framework provides an
infrastructure for dynamic conversion
IConvertible and Convert class, or TypeConverter, but the implementation is
up to the developer.

The sample that I gave
(typeof(MyType))var?

doesn't make much sense because this line can be re-written simply to
(MyType)var and it will compile.

but this (what actually I wanted to demonstrate) is not possible

Type t = var1.GetType();
var1 = (t)var2; // at compile tyme t doesn't have value.
--
Stoitcho Goutsev (100) [C# MVP]

"Nick Weekes" <ni***********@yahoo.co.uk> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Stoitcho,

Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?

Cheers,

Nick

Nov 17 '05 #6
This is just a language syntax, but I guess the reason is that the IL
instruction that this expression emits expects a type metadata token. It
cannot be generated at compile type if you use a variable that doesn't have
value at compile time. Keep in mind that the IL instruction for conversion
*castclass* converts only to/from classes and itnerfaces that are in
base/derived class relationship or the interface is implemented by the type.
All other convrsion techniques like IConvertible, TypeConverter or type
casting operators overloading (C#) is not taken into account. All such
conversions has to be done explicitly by the progeammer or the compiler.
They are not part of the .NET Runtime so to speak.

Dynamic conversion cannot be provided out of the box. The one who writes the
class only know how to convert it to/from another type. For example how
could the runtyme know how to cnonvert from string to Foo. Only me (the
programmer who wrote this foo class) knows how to do that and if this
conversion makes any sense after all. The framework provides an
infrastructure for dynamic conversion
IConvertible and Convert class, or TypeConverter, but the implementation is
up to the developer.

The sample that I gave
(typeof(MyType))var?

doesn't make much sense because this line can be re-written simply to
(MyType)var and it will compile.

but this (what actually I wanted to demonstrate) is not possible

Type t = var1.GetType();
var1 = (t)var2; // at compile tyme t doesn't have value.
--
Stoitcho Goutsev (100) [C# MVP]

"Nick Weekes" <ni***********@yahoo.co.uk> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Stoitcho,

Thanks for the explanation. Why is it not possible to cast an unknown,
for example (typeof(MyType))var?

Cheers,

Nick

Nov 17 '05 #7

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

Similar topics

18
by: Graham Nicholls | last post by:
Hi. I'm having some fun with numbers. I've extraced an image sizes from a jpeg file img_x,img_y=image.getsize() then I'm trying to use those sizes to scale the image, but because python...
2
by: alexqa2003 | last post by:
name1 field is is nvarchar(40). (1)select case when isnumeric(name1) = 1 then cast(name1 as int) else null end as name In (1) when name1 is not numeric, name is null and its type becomes...
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 ...
7
by: James Mcguire | last post by:
Hi, I frequently do non-initialisation type structure assignment via casting: e.g. struct s{int i,j,k;} mys; .... mys=(struct s){3,4,5};
4
by: hsomob1999 | last post by:
I have a class, lets call it Schmuck. It has 2 public properties Name (string) and active (boolean). When I bind to a Repeater, like so: <%#container.dataitem("Name")%> i get the following error:...
4
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...
7
by: lovecreatesbea... | last post by:
Is it always legal to cast expressions of type of multi-dimension array to type of pointer? Including: T to T* , T to T* , T to T* , and so on... For example: int *mtxrot1d(int *p,...
16
by: JoseMariaSola | last post by:
How may operators and operands does (typename) expression has? I'd say one operator, the cast operator, and two operands: typename and expression. But everywhere I read, cast is categorized as...
20
by: raylopez99 | last post by:
Inspired by Chapter 8 of Albahari's excellent C#3.0 in a Nutshell (this book is amazing, you must get it if you have to buy but one C# book) as well as Appendix A of Jon Skeet's book, I am going...
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.