0
0
C Sharp (C#)programming~5 mins

Generic interfaces in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic interface in C#?
A generic interface is an interface that has one or more type parameters. It allows you to define methods and properties that work with any data type specified when the interface is implemented.
Click to reveal answer
beginner
How do you declare a generic interface with one type parameter named T?
You declare it like this: <br>
public interface IExample<T> {<br>    void DoSomething(T item);<br>}
Click to reveal answer
intermediate
Why use generic interfaces instead of non-generic ones?
Generic interfaces provide type safety and code reuse. They let you write flexible code that works with any data type without losing the benefits of compile-time type checking.
Click to reveal answer
beginner
How do you implement a generic interface in a class?
You specify the type when implementing the interface. For example:<br><pre>public class MyClass : IExample&lt;int&gt; {<br>    public void DoSomething(int item) {<br>        // implementation<br>    }<br>}</pre>
Click to reveal answer
intermediate
Can a generic interface have multiple type parameters? Give an example.
Yes, it can. Example:<br>
public interface IPair<T1, T2> {<br>    T1 First { get; }<br>    T2 Second { get; }<br>}
Click to reveal answer
What does the <T> mean in a generic interface declaration?
AIt is a placeholder for a data type specified later
BIt is a method name
CIt is a variable
DIt is a keyword to create an object
How do you specify the type when implementing a generic interface?
ABy providing the type in angle brackets after the interface name
BBy declaring a new interface
CBy using the 'new' keyword
DBy casting the interface
Which of these is a valid generic interface declaration?
Apublic interface ITest { void Do(T item); }
Bpublic class ITest<T> { void Do(T item); }
Cpublic interface ITest<T> { void Do(T item); }
Dpublic interface ITest<T> { T Do(); }
Can a generic interface have properties using the generic type?
AOnly static properties can use the generic type
BYes, properties can use the generic type
CNo, generic interfaces cannot have properties
DNo, only methods can use the generic type
What is the main advantage of using generic interfaces?
AThey allow private methods in interfaces
BThey make code run faster
CThey reduce the number of classes needed
DThey allow code reuse with type safety
Explain what a generic interface is and why it is useful.
Think about how you can write one interface that works with many data types.
You got /4 concepts.
    Describe how to implement a generic interface in a class with an example.
    Remember to specify the type in angle brackets after the interface name.
    You got /4 concepts.