user196546
user196546

Reputation: 2593

C# - Generic interfaces

Where do generic interfaces are quite useful ? ( I am a beginner,so simple example will definitely helpful).

Upvotes: 3

Views: 284

Answers (3)

Andrew Keith
Andrew Keith

Reputation: 7563

Its useful when you need an interface, but you also need to abstract the data type. Simple example

public interface IMyShape<T>
{
   T X { get; }
   T Y { get; }
}

public class IntSquare : IMyShape<int>
{
   int X { get { return 100; } }
   int Y { get { return 100; } }
}

public class IntTriangle : IMyShape<int>
{
   int X { get { return 200; } }
   int Y { get { return 200; } }
}

public class FloatSquare : IMyShape<float>
{
   float X { get { return 100.05; } }
   float Y { get { return 100.05; } }
}

Upvotes: 4

Andrew Hare
Andrew Hare

Reputation: 351748

Generic interfaces are really useful when you want to parameterize the types of one of the members in the interface. Consider the IEnumerable and IEnumerable<T> interfaces. The first iterates Objects whereas the second iterates instances of the type argument supplied for T.

Since interfaces can be generic it allows you to leverage their flexibility while still taking advantage of generics in the same way that you would for a concrete type.

Upvotes: 2

Pavel Minaev
Pavel Minaev

Reputation: 101655

You can look at IEnumerable<T> to begin with.

Upvotes: 3

Related Questions