I'm somewhat new to generics in C#. I have a IResult
interface which has the following properties:
public interface IResult<T>
{
string ResultMessage { get; set; }
T Data { get; set; }
}
The purpose being that inheriting objects will be returning a string message with a payload to the UI. This will be delivered via another object which has detailed information and handles serialize/deserialization, which will contain an IEnumerable
of these objects. However, it needs to hold any IResult, as there may be multiple types in the one object. It must also only hold IResults in that collection. This is the property which is intended to contain them:
public IEnumerable<IResult<dynamic>> Results { get; set; }
The problem is, casting with IEnumerable.Cast()
or an explicit inline cast doesn't work. The presence of dynamic
here was just an attempt by me after doing the same thing with object
and the cast failing then as well.
How can I have my larger payload object accept a collection of IResult<T>
, since none of these work (the first because T is undefined in the context?)
IEnumerable<IResult<T>> Results { get; set; }
//doesn't work as T is undefined, and if defined at the payload level, would result in a single type
IEnumerable<IResult<dynamic>> Results { get; set; }
//doesn't work, the cast fails
IEnumerable<IResult<object>> Results { get; set; }
//doesnt work, the cast fails