I want a generic function that would work with types that have Top
, Bottom
, Right
and Rect
read-only properties - I have
Hey boy you just need this:
Force generic interface implementation in C#
this way you can assume later on that your WhatType
instance will have Left, Bottom and so on...
You haven't specified any conditions for the WhatType
type, so it will accept any type, and only know what every type knows, i.e. only what's defined in the Object
class.
If you want to use anything else in the type, you have to specify what it contains, which you do by specifying that it has to implement an interface or inherit from a class:
internal class MyTemplate<WhatType> where WhatType : BaseType {
Where BaseType
would either be an interface or a class where the Left
property is defined.
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<WhatType> where WhatType : IHasPosition
{
internal static void Work( WhatType what )
{
int left = what.Left;
}
};
Generics is used for type safety. Now without any additional info about WhatType
, how would the compiler know that the instance what
that gets passed in will have a property Left
?
You need something like this
public interface IFoo
{
int Left {get;}
}
and
internal class MyTemplate<WhatType> where WhatType : IFoo {
You have to specify the base class that supports .Left in the where clause or you have to cast what to a type that supports the .Left-property:
internal class MyTemplate<WhatType> where WhatType : YourBaseClassWithLeftProperty
or
internal class MyTemplate<WhatType> {
internal static void Work( WhatType what ) {
YourBaseClassWithLeftProperty yourInstance=what as YourBaseClassWithLeftProperty;
if(null != yourInstance){
int left = yourInstance.Left;
}
}
...
You can specify the type like this:
internal class MyTemplate<WhatType> where WhatType : LeftInterface
Then you could use the .Left
call.
Where LeftInterface
might look like this:
public interface LeftInterface
{
int Left {get; set;}
}