Search code examples
c#.net-coretypesmethod-parameters

Passing type as a parameter


I have a method which takes an object of a certain inherited type and searches for it in the internal data structure...

public (bool,Point) GetItemPosition(IMyBaseType type)
{
    ...
}

So the use of the above method would be something like this:

var (isFound, location) = myDataContainer.GetItemPosition(myDataItem);

In the data structure class, I want to make use of the search method. However, I don't want to have to create an instance of the desired data item (because that has an overhead) - I just want to pass the class type as a value. Currently, I am creating a data item instance...

public bool AddTarget()
{
    var (hasTarget, location) = GetItemPosition(new SomeDataItem().GetType() as IMyBaseType, 0, 0);
    ...
}

How can I pass the class type itself?


Solution

  • Use generics:

    public (bool,Point) GetItemPosition<T>() where T: IMyBaseType
    {
        ...
    }
    

    In the method, you would refer to the passed in type as T. You can check, for example, if an object obj is of type T with is:

    if (obj is T) { ... }
    

    The caller would look like:

    GetItemPosition<SomeDataItem>()