DirectCast - Why is this not working?

  • Thread starter Vagabond Software
  • Start date
V

Vagabond Software

Here is the code:

Dim amountDue As Double
amountDue = Math.Round(DirectCast(strOrderTotal, Double), 2)

This code produces an invalid cast exception. The String variable
strOrderTotal evaluates to "226.27".

Is it not valid to cast a string to a double? I don't want to use CType
because it is my understanding that CType is not CLS compliant. Is that
correct?

carl
 
G

Greg Burns

Why not use Double.Parse(strOrderTotal) ?

AFAIK CType is CLS compliant. It is very hard to code in .NET without it.
:)

Greg
 
C

Colin Neller

<docs>
DirectCast requires an inheritance or implementation relationship between
the data types of the two arguments. This means that one type must inherit
from or implement the other.

DirectCast generates a compiler error if it detects that no inheritance or
implementation relationship exists. But the lack of a compiler error does
not guarantee a successful conversion. If the desired conversion is
narrowing, it could fail at run time. If this happens, the runtime throws an
InvalidCastException error.
</docs>

"String" does not inherit or implement "Double" (or vice versa for that
matter) and therefore fails.
 
H

Herfried K. Wagner [MVP]

Vagabond Software said:
Dim amountDue As Double
amountDue = Math.Round(DirectCast(strOrderTotal, Double), 2)

This code produces an invalid cast exception. The String variable
strOrderTotal evaluates to "226.27".

Is it not valid to cast a string to a double? I don't want to use CType
because it is my understanding that CType is not CLS compliant. Is that
correct?

Either use 'CType' or 'Double.Parse'. I don't think it matters whether or
not 'CType' is CLS-compliant or not because it is used inside the
implementation. DirectCast doesn't work with 'Double' and 'String' because
'String' is not a derived of 'Double' and 'DirectCast' is not used to unbox
a value type in the sample you gave.
 
C

Cor Ligthert [MVP]

Vagebond,

Casting is not converting. That in the C deriving languages world the same
word is used for that is not relevant.

A value is a byte representation on the stack. An object is a schematic
representation depending on its type(class) somewhere in memory. A value can
not be placed in an other representation without converting it.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top