📖 Scenario: Imagine you want to add a new helpful action to a built-in type in C#. For example, you want to add a way to check if a number is even or odd directly on the number itself.
🎯 Goal: You will create an extension method for the built-in int type that checks if a number is even. Then you will use this method to print whether some numbers are even or not.
📋 What You'll Learn
Create a static class called IntExtensions
Inside it, create a public static method called IsEven that extends int
The IsEven method returns true if the number is even, otherwise false
Use the IsEven method on some numbers and print the results
💡 Why This Matters
🌍 Real World
Extension methods let you add new features to existing types without changing their code. This is useful when working with built-in types or libraries you cannot modify.
💼 Career
Knowing how to write extension methods is important for C# developers to write clean, reusable, and readable code that extends functionality in a natural way.
Progress0 / 4 steps
1
Create a static class for extension methods
Create a public static class called IntExtensions to hold extension methods.
C Sharp (C#)
Hint
Extension methods must be inside a static class.
2
Add an extension method IsEven for int
Inside the IntExtensions class, create a public static method called IsEven that extends int using this int number as the first parameter. The method should return true if number % 2 == 0, otherwise false.
C Sharp (C#)
Hint
Use the this keyword before the first parameter to make it an extension method.
3
Use the IsEven extension method on some numbers
In the Main method, create an int variable called num and set it to 4. Then use num.IsEven() to check if it is even and store the result in a bool variable called result.
C Sharp (C#)
Hint
Call the extension method like a normal method on the variable.
4
Print the result of the IsEven check
Add a Console.WriteLine statement to print "4 is even: " followed by the value of result.
C Sharp (C#)
Hint
Use string interpolation with $ and curly braces to include variables in the output.
Practice
(1/5)
1. What is the main purpose of an extension method in C#?
easy
A. To add new methods to existing types without modifying their source code
B. To create a new class that inherits from a built-in type
C. To override existing methods in built-in types
D. To replace built-in types with custom implementations
Solution
Step 1: Understand extension method purpose
Extension methods allow adding new functionality to existing types without changing their original code.
Step 2: Compare options
Replacing built-in types with custom implementations, creating a new class that inherits from a built-in type, or overriding existing methods are different concepts from extension methods.
Final Answer:
To add new methods to existing types without modifying their source code -> Option A
Quick Check:
Extension methods add new actions without changing original types [OK]
Hint: Extension methods add features without changing original code [OK]
2. Which of the following is the correct syntax to declare an extension method for the built-in string type?
easy
A. public void MyMethod(string this str) { }
B. public static void MyMethod(this string str) { }
C. static void MyMethod(string str) { }
D. public static void MyMethod(string str) { }
Solution
Step 1: Recall extension method syntax
Extension methods must be static methods inside static classes, with this before the first parameter type.
Step 2: Check options
Only public static void MyMethod(this string str) { } uses this string str correctly. The other options miss the this keyword or static modifier.
Final Answer:
public static void MyMethod(this string str) { } -> Option B
Quick Check:
Extension method syntax requires 'this' before first parameter [OK]
Hint: Look for 'this' keyword before first parameter in static method [OK]
Common Mistakes:
Omitting the 'this' keyword before the first parameter
Not making the method static
Placing 'this' after the parameter name
3. Given the following code, what will be the output?
public static class StringExtensions {
public static bool IsCapitalized(this string s) {
return !string.IsNullOrEmpty(s) && char.IsUpper(s[0]);
}
}
class Program {
static void Main() {
string word = "Hello";
Console.WriteLine(word.IsCapitalized());
}
}
medium
A. True
B. False
C. Compilation error
D. Runtime exception
Solution
Step 1: Understand the extension method logic
The method checks if the string is not null or empty and if the first character is uppercase.
Step 2: Analyze the input string
The string "Hello" starts with 'H', which is uppercase, so the method returns true.
Final Answer:
True -> Option A
Quick Check:
First letter uppercase in "Hello" means IsCapitalized() returns True [OK]
Hint: Check if first character is uppercase and string is not empty [OK]
Common Mistakes:
Assuming method returns false for capitalized words
Confusing null or empty check logic
Expecting compilation error due to extension method
4. Identify the error in this extension method code:
public static class IntExtensions {
public static bool IsEven(int number) {
return number % 2 == 0;
}
}
medium
A. The method must be inside a non-static class
B. The method cannot return bool
C. The method must be static and have 'this' before the first parameter
D. The method name cannot be 'IsEven'
Solution
Step 1: Check extension method requirements
Extension methods must be static and the first parameter must have the 'this' keyword to specify the type being extended.
Step 2: Identify missing 'this' keyword
The method parameter 'int number' lacks 'this', so it is not a valid extension method.
Final Answer:
The method must be static and have 'this' before the first parameter -> Option C
Quick Check:
Extension methods require 'this' keyword on first parameter [OK]
Hint: Extension method first parameter must have 'this' keyword [OK]
Common Mistakes:
Forgetting 'this' before the first parameter
Placing method in non-static class
Using instance methods instead of static
5. You want to create an extension method for List<int> that returns the sum of all even numbers in the list. Which of the following implementations correctly achieves this?
hard
A. public static int SumEven(this List<int> list) { return list.Sum(n => n % 2); }
B. public int SumEven(List<int> list) { return list.Where(n => n % 2 == 0).Sum(); }
C. public static int SumEven(List<int> list) { return list.Sum(n => n % 2 == 0); }
D. public static int SumEven(this List<int> list) { int sum = 0; foreach(var n in list) { if(n % 2 == 0) sum += n; } return sum; }
Solution
Step 1: Verify extension method signature
public static int SumEven(this List<int> list) { int sum = 0; foreach(var n in list) { if(n % 2 == 0) sum += n; } return sum; } and the version using list.Sum(n => n % 2) have 'this List<int> list' parameter, making them extension methods. The others lack 'this'.
Step 2: Check logic correctness
public static int SumEven(this List<int> list) { int sum = 0; foreach(var n in list) { if(n % 2 == 0) sum += n; } return sum; } sums even numbers correctly using a loop and condition. public static int SumEven(this List<int> list) { return list.Sum(n => n % 2); } sums n % 2 which returns 0 or 1, not the number itself. The others are not extension methods.
Final Answer:
public static int SumEven(this List<int> list) { int sum = 0; foreach(var n in list) { if(n % 2 == 0) sum += n; } return sum; } -> Option D
Quick Check:
Extension method with correct sum logic is public static int SumEven(this List<int> list) { int sum = 0; foreach(var n in list) { if(n % 2 == 0) sum += n; } return sum; } [OK]
Hint: Use 'this' and sum only even numbers correctly [OK]
Common Mistakes:
Missing 'this' keyword for extension method
Incorrect lambda in Sum causing wrong results
Not filtering even numbers before summing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.