What is the output of this C# code using a custom LINQ extension method?
using System; using System.Collections.Generic; using System.Linq; public static class Extensions { public static IEnumerable<int> DoubleEvenNumbers(this IEnumerable<int> source) { foreach (var num in source) { if (num % 2 == 0) yield return num * 2; } } } class Program { static void Main() { var numbers = new List<int> {1, 2, 3, 4, 5}; var result = numbers.DoubleEvenNumbers(); foreach (var n in result) Console.Write(n + " "); } }
Look at which numbers are even and how they are transformed.
The method DoubleEvenNumbers yields only even numbers doubled. 2 becomes 4, 4 becomes 8.
In C#, what does the this keyword before the first parameter in an extension method signify?
Think about how extension methods add functionality to existing types.
The this keyword before the first parameter tells the compiler this method extends that type.
What error will this code produce when compiled?
public static class Extensions { public static IEnumerable<int> FilterOdds(this IEnumerable<int> source) { return source.Where(x => x % 2 == 1); } public static IEnumerable<int> FilterOdds(this List<int> source) { return source.Where(x => x % 2 == 1); } }
Check method signatures and how overload resolution works for extension methods.
No error. The methods have different 'this' parameter types (IEnumerable<int> and List<int>), making them valid overloads. The compiler selects the most specific match at call sites.
Which option shows the correct syntax for an extension method that filters strings by minimum length?
Remember extension methods must be static and the first parameter uses this.
Option C correctly declares a static method with this on the first parameter and includes the extra parameter.
Given these two extension methods, what is the count of items in result?
using System; using System.Collections.Generic; using System.Linq; public static class Extensions { public static IEnumerable<int> MultiplyBy(this IEnumerable<int> source, int factor) { foreach (var n in source) yield return n * factor; } public static IEnumerable<int> FilterGreaterThan(this IEnumerable<int> source, int threshold) { foreach (var n in source) if (n > threshold) yield return n; } } class Program { static void Main() { var numbers = new List<int> {1, 2, 3, 4, 5}; var result = numbers.MultiplyBy(3).FilterGreaterThan(10); Console.WriteLine(result.Count()); } }
Multiply each number by 3, then count how many are greater than 10.
Numbers multiplied by 3: 3,6,9,12,15. Only 12 and 15 are > 10, so count is 2.