C#'s equivalent to VB.Net's DirectCast?

Posted by Collin Sauve on Stack Overflow See other posts from Stack Overflow or by Collin Sauve
Published on 2010-04-21T14:32:54Z Indexed on 2010/04/21 15:33 UTC
Read the original article Hit count: 315

Filed under:
|
|
|
|

This has probably been asked before, but if it has, I can't find it. Does C# have an equivalent to VB.Net's DirectCast? I am aware that it has () casts and the 'as' keyword, but those line up to CType and TryCast.

To be clear, these keywords do the following;

CType/() casts: If it is already the correct type, cast it, otherwise look for a type converter and invoke it. If no type converter is found, throw an InvalidCastException.

TryCast/"as" keyword: If it is the correct type, cast it, otherwise return null.

DirectCast: If it is the correct type, cast it, otherwise throw an InvalidCastException.



EDIT: After I have spelled out the above, some people have still responded that () is equivalent, so I will expand further upon why this is not true.

DirectCast only allows for either Narrowing or Widening conversions on inheritance tree, it does not support conversions across different branches like () does. ie: C#, this compiles and runs:


  //This code uses a type converter to go across an inheritance tree
  double d = 10;
  int i = (int)d;


VB.Net, this does NOT COMPILE


  'Direct cast can only go up or down a branch, never across to a different one.
  Dim d as Double= 10
  Dim i as Integer = DirectCast(d, Integer)


The equivalent in VB.Net to my C# code is CType:


  'This compiles and runs
  Dim d as Double= 10
  Dim i as Integer = CType(d, Integer)


(Edit again, I was originally using strings, I changed it to double... sorry)

© Stack Overflow or respective owner

Related posts about c#

Related posts about vb.net