What is the output of this C# code using an extension method?
using System; public static class StringExtensions { public static string AddHello(this string str) { return "Hello, " + str; } } class Program { static void Main() { string name = "Alice"; Console.WriteLine(name.AddHello()); } }
Extension methods add new methods to existing types without changing them.
The extension method AddHello adds "Hello, " before the string. So calling name.AddHello() returns "Hello, Alice".
Which of the following best explains why extension methods are needed in C#?
Think about how you can add functionality to classes you don't own.
Extension methods let you add methods to existing types without changing their code or using inheritance. This is useful for adding helpers to built-in or third-party classes.
What error will this code produce?
using System; public static class Extensions { public static int Double(this int x) { return x * 2; } } class Program { static void Main() { int number = 5; Console.WriteLine(number.Double()); Console.WriteLine(Extensions.Double(number)); } }
Extension methods can be called like instance methods or static methods with the instance as argument.
The extension method Double multiplies the integer by 2. It can be called as number.Double() or Extensions.Double(number). Both print 10.
Which option shows the correct syntax for defining an extension method in C#?
Extension methods must be static and have 'this' before the first parameter.
Extension methods must be static methods in static classes, with the first parameter preceded by this keyword.
Given that the string class is sealed and cannot be inherited, how can extension methods help add a method IsPalindrome to check if a string reads the same backward?
Which code correctly implements this?
Remember extension methods need this on the first parameter and must return a bool.
Option D correctly defines an extension method on string with this string s and compares the string to its reversed version converted back to string.