I have an interface IApiDataWithProperties. A class called Event implements this interface.
Normally I would be able to cast an object of IApiDataWithProperties to Event (assuming it is one) and for the compiler to let me do that no problem.
In this case, the type is actually a generic TApiData which has a where restriction to interface IApiDataWithProperties. However, I am unable to cast TApiData to Event even with the type restriction. I get Cannot convert type 'TApiData' to 'Event'
Why is this? Am I missing something?
public class Event : IApiDataWithProperties, IXmlSerializable
{
// ...
}
public abstract class AbstractBatchPropertyProcessor<TApiData> : AbstractBatchProcessor<TApiData>, IBatchProcessor
where TApiData : IApiDataWithProperties
{
protected virtual string Build(ConcurrentBag<TApiData> batch)
{
foreach (var newItem in batch)
{
if(newItem is Event)
{
// This cast fails: Cannot convert type 'TApiData' to 'Event'
((Event)newItem).Log();
}
}
// ...
}
}
Edit:
I'm just looking to know why this is a compilation error.
I'm aware this is a strange design, and you wouldn't normally cast like that inside a generic method anyway. This was something I came across when I wanted to add some quick logging info there during a test, and this was the path of least effort.