You don't actually pass a type to a function here, but create new code for every time you use it. To avoid doubt: ({...}) is a "statement expression", which is a GCC extension and not standard C.
"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.
The type parameter is a placeholder for a specific type that the client specifies when they create an instance of the generic type. A generic class cannot be used as-is because it is simply a blueprint for that type.
There are two common approaches. First, you can pass System.Type
object GetColumnValue(string columnName, Type type)
{
// Here, you can check specific types, as needed:
if (type == typeof(int)) { // ...
This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));
The other option would be to use generics:
T GetColumnValue<T>(string columnName)
{
// If you need the type, you can use typeof(T)...
This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);
foo.GetColumnValues(dm.mainColumn, typeof(string))
Alternatively, you could use a generic method:
public void GetColumnValues<T>(object mainColumn)
{
GetColumnValues(mainColumn, typeof(T));
}
and you could then use it like:
foo.GetColumnValues<string>(dm.mainColumn);
You can pass a type as an argument, but to do so you must use typeof
:
foo.GetColumnValues(dm.mainColumn, typeof(int))
The method would need to accept a parameter with type Type
.
where the GetColumns method will call a different method inside depending on the type passed.
If you want this behaviour then you should not pass the type as an argument but instead use a type parameter.
foo.GetColumnValues<int>(dm.mainColumn)
foo.GetColumnValues(dm.mainColumn, typeof(int));
foo.GetColumnValues(dm.mainColumn, typeof(string));
Or using generics:
foo.GetColumnValues<int>(dm.mainColumn);
foo.GetColumnValues<string>(dm.mainColumn);
You can do this, just wrap it in typeof()
foo.GetColumnValues(typeof(int))
public void GetColumnValues(Type type)
{
//logic
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With