📖 Scenario: Imagine you have a list of numbers and you want to find all the even numbers easily. LINQ helps you do this in a simple way. Behind the scenes, LINQ uses something called extension methods to add new abilities to lists without changing their original code.
🎯 Goal: You will create a list of numbers, add an extension method to find even numbers, and then use it to get and print those even numbers.
📋 What You'll Learn
Create a list of integers called numbers with values 1, 2, 3, 4, 5, 6
Create a static class called MyExtensions with an extension method GetEvenNumbers for IEnumerable<int>
Use the extension method GetEvenNumbers on the numbers list to get even numbers
Print the even numbers separated by spaces
💡 Why This Matters
🌍 Real World
Extension methods let developers add useful features to existing classes without changing their code. This is how LINQ works to query collections easily.
💼 Career
Understanding extension methods is important for writing clean, reusable C# code and working with LINQ, which is widely used in software development.
Progress0 / 4 steps
1
Create the list of numbers
Create a list of integers called numbers with these exact values: 1, 2, 3, 4, 5, 6
C Sharp (C#)
Hint
Use List<int> and initialize it with the values inside curly braces.
2
Create the extension method
Create a static class called MyExtensions and inside it create a public static extension method called GetEvenNumbers that takes this IEnumerable<int> source and returns only even numbers using a foreach loop and yield return
C Sharp (C#)
Hint
Extension methods must be inside a static class and have this before the first parameter.
3
Use the extension method to get even numbers
Create a variable called evenNumbers and set it to the result of calling numbers.GetEvenNumbers()
C Sharp (C#)
Hint
Call the extension method directly on the numbers list.
4
Print the even numbers
Use a foreach loop to print each number in evenNumbers separated by spaces on one line
C Sharp (C#)
Hint
Use Console.Write inside the loop to print numbers on the same line separated by spaces.
Practice
(1/5)
1. Why does LINQ in C# rely on extension methods?
easy
A. To add query capabilities to existing types without modifying them
B. To create new classes for each query operation
C. To replace all existing methods in a class
D. To make the code run faster by compiling queries separately
Solution
Step 1: Understand LINQ's design goal
LINQ aims to add query features to existing collections without changing their original code.
Step 2: Role of extension methods
Extension methods allow adding new methods to existing types externally, enabling LINQ queries without modifying those types.
Final Answer:
To add query capabilities to existing types without modifying them -> Option A
Quick Check:
LINQ uses extension methods to extend types [OK]
Hint: Extension methods add features without changing original classes [OK]