Sobes.tech
Junior — Middle

Can you explain the concept of extension methods in LINQ and how they are applied in practice?

sobes.tech AI

Answer from AI

Extension methods in LINQ are static methods that allow adding new methods to existing types without modifying their source code. In the context of LINQ, they enable writing queries to collections in a convenient and readable style.

For example, the extension method Where is applied to collections implementing the IEnumerable<T> interface and returns a filtered sequence.

Example of using an extension method:

var numbers = new List<int> {1, 2, 3, 4, 5};
var evenNumbers = numbers.Where(n => n % 2 == 0);

Here, Where is an extension method that adds filtering functionality to a list of numbers.

In practice, extension methods allow writing expressive and concise code for data manipulation, as well as extending the functionality of existing classes without inheritance or modifying the source code.