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 for a built-in type like
string?You declare a static method inside a static class, and the first parameter has the <code>this</code> keyword followed by the type you want to extend, for example: <br><pre>public static class StringExtensions {
public static bool IsCapitalized(this string s) { ... }
}</pre>Click to reveal answer
intermediate
Can extension methods access private members of the type they extend?
No, extension methods cannot access private or protected members of the type they extend. They only work with the public interface of the type.
Click to reveal answer
intermediate
Why use extension methods instead of inheritance for built-in types?
Built-in types like <code>string</code> are sealed and cannot be inherited. Extension methods let you add functionality without inheritance or modifying the original type.Click to reveal answer
beginner
How do you call an extension method in your code?
You call an extension method as if it were an instance method on the object, for example:
"hello".IsCapitalized(). The compiler translates this to a static method call behind the scenes.Click to reveal answer
What keyword must the first parameter of an extension method have?
✗ Incorrect
The first parameter of an extension method must be preceded by the keyword
this to specify the type being extended.Where must extension methods be declared?
✗ Incorrect
Extension methods must be declared inside a static class.
Can extension methods override existing methods of a type?
✗ Incorrect
Extension methods cannot override existing methods; they only add new methods.
Which of these is a valid extension method signature for
int?✗ Incorrect
The correct syntax uses
this before the type in the first parameter inside a static method.How do you use an extension method named
WordCount on a string variable text?✗ Incorrect
Extension methods are called like instance methods on the variable.
Explain how to create and use an extension method for a built-in type in C#.
Think about how you add new methods without changing the original type.
You got /4 concepts.
Why are extension methods useful for built-in types like string or int?
Consider the limits of inheritance with built-in types.
You got /4 concepts.