tags:

views:

174

answers:

1

Does anyone have a complete list of the conversion operators for VB/C# and how they differ?

So far I know about...

  • value as type [C#]
  • TryCast(value, type) [VB]
  • Convert.ToXxx(value) [any]
  • (type)value [C#]
  • CType(value, type) [VB]
  • DirectCast(value, type) [VB]
  • CXxx(value) [VB]
  • CTypeDynamic [any]
  • implicit conversions when using Option Strict Off [VB]
  • implicit conversions when using dynamic [C#]
  • type value [F#]
  • :> [F#]
  • :?> [F#]

But of course just having the list isn't the same as knowing the subtle differences between each one.

+4  A: 

For F# versus C# on casts/conversions, see

What does this C# code look like in F#? (part one: expressions and statements)

for a short discussion of numeric conversions, boxing conversions, upcasts, and downcasts.

(Note that you list

type value

for F#, I presume you're talking about e.g.

int 'a'

but note that int here is the name of a function in the F# library, rather than the name of a type. See the docs here; in general there is a function named T for each primitive numeric type T, and that function converts its argument to the destination type of the same name.)

Regarding implicit conversions in F#:

  • There's string -> PrintfFormat (as part of the magic for typesafe printf)
  • There's upcasts at method calls arguments and property/array assignments that enables you to do e.g. f(dog) or person.Pet <- dog when an Animal is expected. This also works for known nominal types for collection literals, e.g. let controls : Control list = [button; form; window]
  • There's a function-to-delegate conversion at method call arguments, which enable e.g. new Thread(fun() -> ()) where the F# function is converted to the ThreadStart delegate.
  • There's ref to byref conversion at method call arguments, which enables you to pass a ref to e.g. an out parameter.

I think those are it - there are very few implicit conversions in F#.

Brian
VB is similar in that most type casting operators are either library functions or could be changed into library functions. The only ones that are actual syntax are CType, TryCast, and DirectCast.
Jonathan Allen