Visual Basic equivalent of C# type check

C#vb.net

C# Problem Overview


What is the Visual Basic equivalent of the following C# boolean expression?

data.GetType() == typeof(System.Data.DataView)

Note: The variable data is declared as IEnumerable.

C# Solutions


Solution 1 - C#

As I recall

TypeOf data Is System.Data.DataView

Edit:
As James Curran pointed out, this works if data is a subtype of System.Data.DataView as well.

If you want to restrict that to System.Data.DataView only, this should work:

data.GetType() Is GetType(System.Data.DataView)

Solution 2 - C#

Just thought I'd post a summary for the benefit of C# programmers:

C# val is SomeType

      In VB.NET: TypeOf val Is SomeType

      Unlike Is, this can only be negated as Not TypeOf val Is SomeType

C# typeof(SomeType)

      In VB.NET: GetType(SomeType)

C# val.GetType() == typeof(SomeType)

      In VB.NET: val.GetType() = GetType(SomeType)

      (although Is also works, see next)

C# val.ReferenceEquals(something)

      In VB.NET: val Is something

      Can be negated nicely: val IsNot something


C# val as SomeType

      In VB.NET: TryCast(val, SomeType)

C# (SomeType) val

      In VB.NET: DirectCast(val, SomeType)

      (except where types involved implement a cast operator)

Solution 3 - C#

You could also use TryCast and then check for nothing, this way you can use the casted type later on. If you don't need to do that, don't do it this way, because others are more efficient.

See this example:

VB:

    Dim pnl As Panel = TryCast(c, Panel)
    If (pnl IsNot Nothing) Then
        pnl.Visible = False
    End If

C#

Panel pnl = c as Panel;
if (pnl != null) {
	pnl.Visible = false;
}

Solution 4 - C#

Try this.

GetType(Foo)

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
QuestionStevenView Question on Stackoverflow
Solution 1 - C#PowerlordView Answer on Stackoverflow
Solution 2 - C#Roman StarkovView Answer on Stackoverflow
Solution 3 - C#Nick N.View Answer on Stackoverflow
Solution 4 - C#SubZeroView Answer on Stackoverflow