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

Extension methods for built-in types in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Astatic
Bref
Cpublic
Dthis
Where must extension methods be declared?
AInside a static class
BInside any class
CInside an interface
DInside a sealed class
Can extension methods override existing methods of a type?
ANo, they cannot override existing methods
BYes, always
COnly if the method is virtual
DOnly for built-in types
Which of these is a valid extension method signature for int?
Astatic bool IsEven(int this number)
Bpublic static bool IsEven(this int number)
Cpublic bool IsEven(int this number)
Dpublic static bool IsEven(int number)
How do you use an extension method named WordCount on a string variable text?
AWordCount.text()
BWordCount(text)
Ctext.WordCount()
Dtext->WordCount()
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.