Suppose I have a class that has a collection. I want to make a generic method to access certain types of objects within that collection. Basically what I want is:
That is what I would like. The problem is when I try to compile it gives me an error:Code:class MyCollection { List<MyObject> storedObjects; public T GetFirstObjectOfType<T>() { foreach(MyObject obj in storedObjects) { if(obj is T) return (T) obj; } return null; } }
Cannot convert type MyObject to 'T'
How can I get around this. I know that if I change it to:
It will work, but now I am limited in the types that I can search for. For example if I want to search for an object that implements a specific interface I can't because that interface is not of type MyObject.Code:public T GetFirstObjectOfType<T>() where T : MyObject
So for example if I wanted to do something like:
This won't work because IDisposable does not inherit MyObject.Code:IDisposable disposableObject = collection.GetFirstObjectOfType<IDisposable>();




Reply With Quote