I want to write a method which searches for an object in my list, which can contain multiple inherited types.
public class MyClass
{
public readonly List<parentType> objects = new List<parentType>();
public parentType GetObject(Type type, string tag)
{
foreach (parentType _object in objects)
{
if (_object.GetType() == type)
{
if (tag == _object.tag)
{
return _object;
}
}
}
return null;
}
}
But when I call .GetObject(childType, "tag") I get CS0119: 'childType' is a type, which is not valid in the given context.
What should I do? Thanks.
CodePudding user response:
You have several possibilities here:
use
typeof
-GetObject(typeof(childType), "tag")
rewrite your function in generic way and use type as generic parameter
public parentType GetObject<T>(string tag) where T: parentType { //use T as the type to search }
and then call it
GetObject<childType>("tag");
In some cases it may be also usefull to use generic parameter to return more concrete type
T GetObject<T>(string tag) where T: parentType { }
Moreover (but a little offtopic) you can use LINQ to get more simple and idiomatic solution
public T GetObject<T>(string tag) where T: parentType { return objects.OfType<T>().FirstOrDefault(obj => obj.tag == tag); }