📖 Scenario: Imagine you want to add a new feature to the string type in C# without changing its original code. You will create an extension method that adds a simple greeting to any string.
🎯 Goal: Build a C# program that defines an extension method called Greet for the string type. This method will return a greeting message using the original string. Then, use this method on a string variable and print the result.
📋 What You'll Learn
Create a static class called StringExtensions
Inside it, create a public static method called Greet that extends string
The Greet method should return a string formatted as "Hello, {original string}!"
Use the Greet method on a string variable called name
Print the result of calling name.Greet()
💡 Why This Matters
🌍 Real World
Extension methods let you add new features to existing types without changing their original code. This is useful when working with libraries or built-in types.
💼 Career
Many C# developers use extension methods to write cleaner, more readable code and to add helpful utilities to existing types.
Progress0 / 4 steps
1
Create a string variable
Create a string variable called name and set it to the value "Alice".
C Sharp (C#)
Hint
Use string name = "Alice"; to create the variable.
2
Create a static class for extension methods
Create a public static class called StringExtensions to hold extension methods.
C Sharp (C#)
Hint
Use public static class StringExtensions { } to create the class.
3
Add the extension method Greet
Inside the StringExtensions class, create a public static method called Greet that extends string using the this keyword. The method should return a string formatted as "Hello, {original string}!".
C Sharp (C#)
Hint
Use public static string Greet(this string str) and return the greeting with $"Hello, {str}!".
4
Use the extension method and print the result
Call the Greet method on the name variable and print the result using Console.WriteLine.
C Sharp (C#)
Hint
Use Console.WriteLine(name.Greet()); to print the greeting.
Practice
(1/5)
1. What is the main purpose of an extension method in C#?
easy
A. To override existing methods in a class
B. To create new classes that inherit from existing ones
C. To add new methods to existing types without modifying their source code
D. To define constructors for existing classes
Solution
Step 1: Understand extension method purpose
Extension methods allow adding new functionality to existing types without changing their original code.
Step 2: Compare with other options
Options B, C, and D describe inheritance, overriding, and constructors, which are different concepts.
Final Answer:
To add new methods to existing types without modifying their source code -> Option C
Quick Check:
Extension methods add methods without changing original type [OK]
Hint: Extension methods add functionality without changing original code [OK]
2. Which of the following is the correct syntax to declare an extension method in C#?
easy
A. public void MyExtension(string this str) { }
B. public static void MyExtension(this string str) { }
C. static public void MyExtension(string str) { }
D. public static void MyExtension(string str) { }
Solution
Step 1: Check extension method declaration rules
Extension methods must be static methods inside static classes, and the first parameter must have the 'this' keyword before the type.
Step 2: Analyze each option
public static void MyExtension(this string str) { } correctly uses 'public static void' and 'this string str'. public void MyExtension(string this str) { } misplaces 'this'. static public void MyExtension(string str) { } misses 'this'. public static void MyExtension(string str) { } misses 'this' keyword.
Final Answer:
public static void MyExtension(this string str) { } -> Option B
Quick Check:
Extension method syntax requires 'this' before first parameter [OK]
Hint: Remember 'this' before first parameter in static method [OK]
Common Mistakes:
Omitting 'this' keyword before the first parameter
Placing 'this' after the parameter type
Not making the method static
3. What will be the output of the following code?
public static class StringExtensions {
public static int WordCount(this string str) {
return str.Split(' ').Length;
}
}
string sentence = "Hello world from C#";
int count = sentence.WordCount();
Console.WriteLine(count);
medium
A. 4
B. 1
C. 0
D. Compilation error
Solution
Step 1: Understand the extension method behavior
The method WordCount splits the string by spaces and returns the number of parts.
Step 2: Count words in the string
The string "Hello world from C#" has 4 words separated by spaces, so the method returns 4.
Final Answer:
4 -> Option A
Quick Check:
Word count of "Hello world from C#" = 4 [OK]
Hint: Count words by splitting string on spaces [OK]
Common Mistakes:
Forgetting to make the extension method static
Assuming Split returns empty array for non-empty string
Expecting compilation error due to extension method
4. Identify the error in the following extension method code:
public static class IntExtensions {
public static bool IsEven(int number) {
return number % 2 == 0;
}
}
medium
A. The method is not static
B. The class is not static
C. The method should return int instead of bool
D. The first parameter is missing the 'this' keyword
Solution
Step 1: Check extension method parameter syntax
Extension methods require the first parameter to have the 'this' keyword before the type to indicate the extended type.
Step 2: Analyze the code
The method IsEven has 'int number' as parameter but lacks 'this' keyword, so it is not a valid extension method.
Final Answer:
The first parameter is missing the 'this' keyword -> Option D
Quick Check:
Extension method needs 'this' before first parameter [OK]
Hint: Extension method's first parameter must start with 'this' [OK]
Common Mistakes:
Forgetting 'this' keyword on first parameter
Making method non-static
Not declaring class as static
5. You want to create an extension method IsNullOrEmpty for string that returns true if the string is null or empty. Which of the following is the correct implementation?
hard
A. public static bool IsNullOrEmpty(this string str) { return str == null || str == ""; }
B. public bool IsNullOrEmpty(string str) { return str == null || str == ""; }
C. public static bool IsNullOrEmpty(string str) { return str == null || str == ""; }
D. public static bool IsNullOrEmpty(this string str) { return str.Length == 0; }
Solution
Step 1: Check extension method signature
The method must be static and have 'this' before the first parameter type to be an extension method.
Step 2: Verify method logic
public static bool IsNullOrEmpty(this string str) { return str == null || str == ""; } correctly checks if the string is null or empty. public static bool IsNullOrEmpty(this string str) { return str.Length == 0; } misses null check, which causes error if str is null.
Final Answer:
public static bool IsNullOrEmpty(this string str) { return str == null || str == ""; } -> Option A
Quick Check:
Extension method with 'this' and null check is correct [OK]
Hint: Check null before accessing string properties in extension [OK]
Common Mistakes:
Omitting 'this' keyword on first parameter
Not checking for null before accessing Length
Making method non-static
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.