C# "as" operator equivalent in VB.Net

M

Mythran

Since there is no (or I haven't found one) an equivalent in VB.Net to C#'s
"as" operator, I decided to try writing a generic method to perform a
similar operation....any thoughts or suggestions on what I have thus far?

Private Function [As](Of T)(ByVal instance As Object) As T
If TypeOf instance Is T
Return DirectCast(instance, T)
End If
Return Nothing
End Function

Any thoughts or suggestions?

use would be:

Dim b As Control = New Button()
Dim a As Button = [As](Of Button)(b)
If a IsNot Nothing
' b is a control that is a button and not null.
End If


What d'ya think? The alternative to using this method would be:

Dim b As Control = New Button()
Dim a As Button
If TypeOf b Is Button
a = DirectCast(b, Button)
End If

If b IsNot Nothing
' b is a control that is a button and not null.
End If



??? :)

Note: Code above may not compile...I wrote it off the top of my head and
didn't perform testing on it...yet.

Thanks,
Mythran
 
O

(O)enone

Mythran said:
Since there is no (or I haven't found one) an equivalent in VB.Net to
C#'s "as" operator, I decided to try writing a generic method to perform
a similar operation....any thoughts or suggestions on what I have thus far?

I'm not familiar with the C# "as" operator, but from your code it looks
like it does the same thing as VB's TryCast() function. If it can cast
the object to the specified type then it will, otherwise it returns Nothing.
 
H

Herfried K. Wagner [MVP]

(O)enone said:
I'm not familiar with the C# "as" operator, but from your code it looks
like it does the same thing as VB's TryCast() function. If it can cast the
object to the specified type then it will, otherwise it returns Nothing.

Yes, that's the equivalent. However, note that 'TryCast' is an
operator/keyword and not a function.
 
M

Mythran

Herfried K. Wagner said:
Yes, that's the equivalent. However, note that 'TryCast' is an
operator/keyword and not a function.

Doh! Always AFTER I figure out another way to do it....thanks Herfried...
:)

Mythran
 
M

Mythran

(O)enone said:
I'm not familiar with the C# "as" operator, but from your code it looks
like it does the same thing as VB's TryCast() function. If it can cast the
object to the specified type then it will, otherwise it returns Nothing.

Thanks (O)enone....TryCast is the way to go.

Mythran
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top