Background
I encounter an generics error and can easily fix it by adding a cast.
But why do I have to add the (IIndexTableDefs)
as the returned value is already the type asked for?
public class IndexTableDefinitionsController : ParameterDefinitionsBaseController<IIndexTableDef>
{
internal override IIndexTableDefs GetDefinitions<IIndexTableDefs>()
=> Core.StaticDefinitions.Instance.IndexTableDefs;
}
reports an error :
Error CS0266 Cannot implicitly convert type 'SNG.LccNion.Intf.IIndexTableDefs' to 'IIndexTableDefs'. An explicit conversion exists (are you missing a cast?) SNG.LccNion.API S:\Sources\LCCNion\Source\SNG.LccNion.API\Controllers\Definitions\IndexTableDefinitionsController.cs 17 Active
when I add the cast like so:
public class IndexTableDefinitionsController : ParameterDefinitionsBaseController<IIndexTableDef>
{
internal override IIndexTableDefs GetDefinitions<IIndexTableDefs>()
=> (IIndexTableDefs) Core.StaticDefinitions.Instance.IndexTableDefs;
}
the error message goes away. I fail to understand why the error appears as the requested IndexTableDefs
property is already of type IIndexTableDefs
(from the same name space, there is no other IIndexTableDefs
in my sources)
public interface IStaticDefinitions
{
....
public IIndexTableDefs IndexTableDefs { get; }
....
}
the abstract base routine looks like this:
public abstract class DefinitionBaseController<IItemType> : LccNionBaseController
where IItemType : class, IGenericIDDescriptive<IItemType>, IIDDescriptive
{
.....
internal abstract ICollectionType GetDefinitions<ICollectionType>()
where ICollectionType:IGenericIDDescriptives<IItemType>;
.....
}
Q: - a (hopefully simple) explanation why this happens, could it be a compiler issue?
(Using VS2022)
CodePudding user response:
Because you've just defined a generic method, IIndexTableDefs
in the scope is a generic type parameter, not the interface.
IIndexTableDefs GetDefinitions<IIndexTableDefs>()
is equivalent to
T GetDefinitions<T>()