- 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
Using the abstract modifier in C#
This C# coding challenge looks at how the abstract modifier works in C# and why an inherited abstract class won't compile.Write a C# function to convert MPH to KPH
Take our coding challenge to write a C# function with the necessary parameters that converts miles-per-hour (MPH) to kilometres-per-hour (KPH) and vice-versa.
Contains online code editor