- Home
- .NET coding challenges
- Add an extension method to a C# class
Adding an extension method to a class in C#
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?
Give us your anonymous feedback regarding this page, or any other areas of the website.
Related challenges
Work out the number of days between two dates
Write a C# function to work out the difference between two dates and return the number of days in this coding challenge.
Contains online code editor