tags:

views:

192

answers:

6

What is the equivalent in VB.Net of the C# As keyword, as in

var x = y as String;
if (x == null) ...
+2  A: 

Dim x = TryCast(y, [String])

Oskar Kjellin
A: 

Dim x = TryCast(y, [String])

From: http://www.developerfusion.com/tools/convert/csharp-to-vb/

Dustin Laine
+2  A: 

TryCast:

Dim x = TryCast(y, String)
if (x Is Nothing) ...
Guffa
+10  A: 

It is TryCast:

Dim x As String = TryCast(y, String)
If x Is Nothing Then ...
Hans Passant
+1 Although I believe `TryCast` is not **exactly** equivalent to `as` because `TryCast` doesn't work for value types?
MarkJ
@Mark: The *as* operator doesn't work on value types in C# either.
Hans Passant
@nobugz: Well it works for nullable value types... You can do: var x = y as int?; if (x == null) ... so you should be able to do Dim x = TryCast(y, System.Nullable(Of Integer)) in VB
JoelFan
@JoelFan, @nobugz. Oops. Let's try again. I believe `as` can convert value types into **nullable** types but `TryCast` can't? http://stackoverflow.com/questions/746767/how-to-acheive-the-c-as-keyword-for-value-types-in-vb-net/746914#746914
MarkJ
This only works in very select cases because C# automatically applies a boxing conversion to "y". It cannot convert, say, a double to an int?
Hans Passant
+3  A: 

Trycast is what you're looking for.

Dim x = TryCast(y, String)
Morten Anderson
+1  A: 

Here you go:

C# code:

var x = y as String;
if (x == null) ...

VB.NET equivalent:

Dim x = TryCast(y, String)
If (x Is Nothing) ...
Alex Essilfie