I want a generic function that would work with types that have Top
, Bottom
, Right
and Rect
read-only properties - I have
C# generics look similar to C++ templates, but they're actually quite different. C# generics are strongly typed, so you can't call a member that is not statically known.
In order to be able to call Left
on an object of type WhatType
, you have to specify that WhatType
implements an interface or inherits from a class that defines Left
, using a generic constraint. For instance:
interface IHasPosition
{
int Left { get; }
int Top { get; }
}
internal class MyTemplate where WhatType : IHasPosition
{
internal static void Work( WhatType what )
{
int left = what.Left;
}
};