Recall & Review
beginner
What is an extension method in C#?
An extension method is a special kind of static method that allows you to add new methods to existing types without modifying their source code or creating a new derived type.
Click to reveal answer
beginner
How do you declare an extension method in C#?
You declare an extension method as a static method inside a static class. The first parameter has the keyword
this before the type it extends.Click to reveal answer
intermediate
Why must the class containing extension methods be static?Because extension methods are static methods, the class that holds them must also be static to group these methods logically and prevent instantiation.Click to reveal answer
beginner
Example: What does this extension method do?<br>
public static bool IsEven(this int number) { return number % 2 == 0; }This method adds
IsEven() to all integers. It returns true if the number is even (divisible by 2), otherwise false.Click to reveal answer
beginner
How do you use an extension method once it is declared?
You call it like a regular instance method on the type it extends. For example, if
IsEven() extends int, you can call 5.IsEven().Click to reveal answer
Which keyword is required before the first parameter in an extension method?
✗ Incorrect
The
this keyword before the first parameter tells the compiler this is an extension method for that type.Where must extension methods be declared?
✗ Incorrect
Extension methods must be declared inside a static class.
What type of method is an extension method?
✗ Incorrect
Extension methods are static methods that appear as if they are instance methods.
How do you call an extension method on a string variable named
text?✗ Incorrect
You call an extension method like an instance method on the variable, e.g.,
text.Method().Can extension methods access private members of the type they extend?
✗ Incorrect
Extension methods cannot access private members of the type they extend because they are static methods outside the type.
Explain how to write and use an extension method in C#.
Think about how you add a new method to an existing type without changing its code.
You got /4 concepts.
What are the benefits of using extension methods?
Consider how extension methods help when you want new features on types you don't own.
You got /4 concepts.