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

Extension method syntax 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 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?
Aref
Bstatic
Cpublic
Dthis
Where must extension methods be declared?
AInside any class
BInside a static class
CInside an interface
DInside a struct
What type of method is an extension method?
AStatic method
BAbstract method
CVirtual method
DInstance method
How do you call an extension method on a string variable named text?
Atext.Method()
BExtensionClass.Method(text)
CMethod(text)
DCallExtension(text)
Can extension methods access private members of the type they extend?
AYes, always
BOnly if in the same namespace
CNo, they cannot
DOnly if marked internal
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.