VB.NET equivalent of C# "As"

.Netvb.net

.Net Problem Overview


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

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

.Net Solutions


Solution 1 - .Net

It is TryCast:

Dim x As String = TryCast(y, String)
If x Is Nothing Then ...

Solution 2 - .Net

Trycast is what you're looking for.

Dim x = TryCast(y, String)

Solution 3 - .Net

TryCast:

Dim x = TryCast(y, String)
if (x Is Nothing) ...

Solution 4 - .Net

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) ...

Solution 5 - .Net

Dim x = TryCast(y, [String])

Solution 6 - .Net

Solution 7 - .Net

You can use it with ?:

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

It allows you to manage nullable without if :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoelFanView Question on Stackoverflow
Solution 1 - .NetHans PassantView Answer on Stackoverflow
Solution 2 - .NetMorten AndersonView Answer on Stackoverflow
Solution 3 - .NetGuffaView Answer on Stackoverflow
Solution 4 - .NetAlex EssilfieView Answer on Stackoverflow
Solution 5 - .NetOskar KjellinView Answer on Stackoverflow
Solution 6 - .NetDustin LaineView Answer on Stackoverflow
Solution 7 - .NetevanboissonnotView Answer on Stackoverflow