I am trying to pass a type through to a method where I can check if it 'is' a certain type. However the code I have below does not compile and I am wondering whats wrong. The compile error is: type or namespace name 'dataType' could not be found.
public static List<object> findType(Type dataType)
{
List<object> items = new List<object>();
foreach (KeyValuePair<int, object> entry in DataSource.ItemPairs)
{
if (entry.Value != null && entry.Value is dataType)
{
items.Add(entry.Value);
}
}
return items;
}
When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that's sort of a hybrid between pass-by-value and pass-by-reference.
What is Actually Passed to a Method? The data that is passed to a method is used inside the method to accomplish tasks. Definition clarification: What is passed "to" a method is referred to as an "argument". The "type" of data that a method can receive is referred to as a "parameter".
When a parameter is passed to the method, it is called an argument.
Both values and references are stored in the stack memory. Arguments in Java are always passed-by-value. During method invocation, a copy of each argument, whether its a value or reference, is created in stack memory which is then passed to the method.
is
operator expects a type name, not the Type
instance.So the type should be known at compile time.
However you can use, IsAssignableFrom
method to check if the types are compatible:
if (entry.Value != null && dataType.IsAssignableFrom(entry.Value.GetType())
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