Challenge - 5 Problems
Extension Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extension method call
What is the output of this C# program using an extension method?
C Sharp (C#)
using System; public static class StringExtensions { public static string AddExclamation(this string s) { return s + "!"; } } class Program { static void Main() { string greeting = "Hello"; Console.WriteLine(greeting.AddExclamation()); } }
Attempts:
2 left
💡 Hint
Look at what the extension method does to the string.
✗ Incorrect
The extension method AddExclamation adds an exclamation mark to the string. So calling greeting.AddExclamation() returns "Hello!".
❓ Predict Output
intermediate2:00remaining
Extension method with value type
What is the output of this C# code using an extension method on an int?
C Sharp (C#)
using System; public static class IntExtensions { public static int Square(this int x) { return x * x; } } class Program { static void Main() { int number = 4; Console.WriteLine(number.Square()); } }
Attempts:
2 left
💡 Hint
The extension method returns the number multiplied by itself.
✗ Incorrect
The Square extension method returns the input integer multiplied by itself, so 4 * 4 = 16.
🔧 Debug
advanced2:00remaining
Identify the error in extension method syntax
Which option contains the syntax error in defining an extension method?
C Sharp (C#)
public static class Extensions { public static int Double(int x) { return x * 2; } }
Attempts:
2 left
💡 Hint
Check the method parameter for extension method syntax.
✗ Incorrect
Extension methods must be static and the first parameter must have the 'this' keyword to specify the type being extended.
🧠 Conceptual
advanced2:00remaining
Extension method resolution priority
Given a class with an instance method and an extension method with the same name and signature, which method is called when invoked on an instance?
Attempts:
2 left
💡 Hint
Instance methods have higher priority than extension methods.
✗ Incorrect
If a class has an instance method with the same signature as an extension method, the instance method is called. Extension methods are only used if no instance method matches.
❓ Predict Output
expert3:00remaining
Output of chained extension methods
What is the output of this C# program using chained extension methods on a string?
C Sharp (C#)
using System; public static class StringExtensions { public static string AddPeriod(this string s) { return s + "."; } public static string ToUpperCase(this string s) { return s.ToUpper(); } } class Program { static void Main() { string text = "hello"; string result = text.AddPeriod().ToUpperCase(); Console.WriteLine(result); } }
Attempts:
2 left
💡 Hint
Check the order of method calls and their effects on the string.
✗ Incorrect
The string "hello" first gets a period added, becoming "hello.", then it is converted to uppercase, resulting in "HELLO.".