85

What is the equivalent in VB.NET of the C# As keyword, as in the following?

var x = y as String;
if (x == null) ...
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
JoelFan
  • 37,465
  • 35
  • 132
  • 205

7 Answers7

110

It is TryCast:

Dim x As String = TryCast(y, String)
If x Is Nothing Then ...
nloewen
  • 1,279
  • 11
  • 18
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 6
    +1 Although I believe `TryCast` is not **exactly** equivalent to `as` because `TryCast` doesn't work for value types? – MarkJ Mar 15 '10 at 23:24
  • 9
    @Mark: The *as* operator doesn't work on value types in C# either. – Hans Passant Mar 16 '10 at 00:11
  • 2
    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 Mar 16 '10 at 01:41
  • @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 Mar 16 '10 at 13:52
  • 2
    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 Mar 16 '10 at 15:19
  • 1
    @HansPassant C# will hardly ever "implicity" convert one primitive type (or any type) to another, you use the Convert.ToXXX method – enorl76 Aug 16 '14 at 20:04
9

Trycast is what you're looking for.

Dim x = TryCast(y, String)
Stewbob
  • 16,759
  • 9
  • 63
  • 107
Morten Anderson
  • 2,301
  • 15
  • 20
6

TryCast:

Dim x = TryCast(y, String)
if (x Is Nothing) ...
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
6

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
  • 12,339
  • 9
  • 70
  • 108
4

Dim x = TryCast(y, [String])

Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
3
Dim x = TryCast(y, [String])

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

Dustin Laine
  • 37,935
  • 10
  • 86
  • 125
0

You can use it with ?:

TryCast(item, String)?.Substring(10)

It allows you to manage nullable without if :)

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108