Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'is' when type passed in through method?

Tags:

syntax

c#

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;
}
like image 778
user1584120 Avatar asked Jan 06 '15 09:01

user1584120


People also ask

When an object is passed to a method in Java it is passed by?

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.

Is passed to a method?

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".

What is it called when a parameter is passed to the method?

When a parameter is passed to the method, it is called an argument.

How data is passed to methods in Java?

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.


1 Answers

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())
like image 163
Selman Genç Avatar answered Sep 21 '22 04:09

Selman Genç