Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass a "type" as an argument?

I want to do something like the following in VB.NET, is it possible?

Function task(value as Object, toType as Type)

   Return DirectCast(value, toType)

End Function
like image 242
Robin Rodricks Avatar asked Jul 02 '09 13:07

Robin Rodricks


People also ask

Can I pass a type as a parameter C#?

The basic data types can be passed as arguments to the C# methods in the same way the object can also be passed as an argument to a method.

Can you pass a type Golang?

You can't. You can only pass a value, and CustomStruct is not a value but a type. Using a type identifier is a compile-time error. (Also don't forget that this returns an empty string for anonymous types such as []int .)

Do you pass parameters or arguments?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.

What is type arguments C#?

The type argument for this particular class can be any type recognized by the compiler. Any number of constructed type instances can be created, each one using a different type argument, as follows: C# Copy.


2 Answers

Yes. There is System.Type. You may actually want to do a Generic however.

Function SomeFunction(Of T)(obj As Object) As T
    '' Magic
End Function
like image 83
Daniel A. White Avatar answered Sep 20 '22 16:09

Daniel A. White


Great Answer - Here is a generic function to do the same:

Public Sub BindListControlToEnum(Of T)(ListCtrl As ListControl)
    Dim itemValues As Array = System.Enum.GetValues(GetType(T))
    Dim itemNames As Array = System.Enum.GetNames(GetType(T))
    For i As Integer = 0 To itemNames.Length - 1
        Dim item As New ListItem(itemNames(i), itemValues(i))
        ListCtrl.Items.Add(item)
    Next
End Sub

Call it like this:

BindDropdownToEnum(Of MyClass.MyEnum)(MyRadioButtonListControl)
like image 45
Dominic Turner Avatar answered Sep 18 '22 16:09

Dominic Turner