Visual Basic equivalent of C# type check
C#vb.netC# 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:
val is SomeType
C# In VB.NET: TypeOf val Is SomeType
Unlike Is
, this can only be negated as Not TypeOf val Is SomeType
typeof(SomeType)
C# In VB.NET: GetType(SomeType)
val.GetType() == typeof(SomeType)
C# In VB.NET: val.GetType() = GetType(SomeType)
(although Is
also works, see next)
val.ReferenceEquals(something)
C# In VB.NET: val Is something
Can be negated nicely: val IsNot something
val as SomeType
C# In VB.NET: TryCast(val, SomeType)
(SomeType) val
C# 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)