Published: Monday 23 October 2023
Extension methods can be used to add static methods to an existing class or type without modifying the original copy of it.
Although they are static, they are called as part of the original instance by importing the namespace where the extension method exists.
You can find out more about extension methods on the Microsoft website.
We have this CategoryService
class:
public class CategoryService {
public List<string> GetAllCategoryNames() {
return new List<string>();
}
}
And we have this CategoryHelper
static class that has a GetAllCategoryIds
method added.
public static class CategoryHelper {
public static List<int> GetAllCategoryIds() {
return new List<int>();
}
}
We want to add the GetAllCategoryIds
method to the CategoryService
as an extension method. How do we do that?