Type conversion "as" in VB .NET

  • Thread starter Thread starter Hayato Iriumi
  • Start date Start date
H

Hayato Iriumi

When converting a type to another using CType and if the type conversion
fails, it throw an exception. However, in C#, there is a keyword "as" which
only makes the variable Nothing (null) without throwing an exception. Is
there a plan at Microsoft VB .NET team to include a keyword equivalent to
"as"?
 
I should hope not.

If I code a CType(...) and it fails then I damnned well want to know about
it.
 
Absolutely, you want to know about the exception, but there may be a
situation where you want to handle the failure of type conversion by
checking whether the variable is Nothing or not. If the variable is not
nothing, then the type conversion succeeded. Here is the example.

[VB .NET]
Dim MyObject As MyType

Try
MyObject = CType(SomeObject, MyType)
Catch
MyObject = Nothing
End Try

If Not MyObject Is Nothing Then
' Do Some process
End If

[C#]
MyType MyObject = SomeObject as MyType;

if (MyObject != null)
{
' Do some process
}


VB .NET code is significantly more. And I assume that since it uses
exception to handle situation like it, performance cost may be higher in VB
..NET than in C#...
 
Hi Stephany,

The 'as' keyword in C#, is just a shorthand. It doesn't necessarily hide
anything away from you. Assigning some object to a variable of a given type
when it is not that type doesn't fail. It successfully sets the variable to
null.

C#
object o = 24;

SomeSub (o as string); // passes null
string s = o as string; // s = null


VB
Dim o As Object
o = 24
Dim s As String
If o.GetType Is GetType(String) = False Then
s = Nothing
Else
s = o
End If
SomeSub (s) 'Needs the whole If statement first.

It's just VB windyness. That's all.

Regards,
Fergus
 
Yeah, yeah :-)

VB
Dim o As Object
o = 24
Dim s As String
If TypeOf o Is String Then
s = o
Else
s = Nothing
End If
SomeSub (s) 'Needs the whole If statement first.

Still windy.

Regards,
Fergus
 
Hayato,
When converting a type to another using CType and if the type conversion
fails, it throw an exception.
BTW: You do know that using DirectCast is generally better than using CType
when casting reference types?
Is there a plan at Microsoft VB .NET team to include a keyword
equivalent to "as"?

Not that I am aware of. Some items identified for the next version of VB.NET
are documented at:

http://msdn.microsoft.com/vstudio/productinfo/roadmap.aspx

As Fergus stated, its a shorthand. A very handy shorthand. In addition to
CType & DirectCast I can see a use for "as".

You could use the Microsoft.Com Product Feedback system (MS Wish) to submit
a request that this be included:
http://register.microsoft.com/mswish/suggestion.asp?&SD=GN&LN=EN-US&gssnb=1

Hope this helps
Jay
 
Back
Top