Junior
What is an extension method in C#?
sobes.tech AI
Answer from AI
Extension Method - is a static method that can be called as if it were a method of the extended type, although it is actually defined outside of that type.
Main features:
- It is a static method declared in a static class.
- The first parameter of the extension method must be marked with the
thiskeyword and indicate the type you want to extend. - Extension methods do not have access to private and protected members of the extended type.
- They allow adding functionality to existing types without modifying their source code or using inheritance.
Example of creation and usage:
-
Defining a static class and a static extension method:
public static class StringExtensions // Static class { public static string ToTitleCase(this string input) // Extension method for string type { if (string.IsNullOrEmpty(input)) { return input; } // Simple logic to convert to Title Case return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()); } } -
Using the extension method:
string myString = "hello world"; string titleCaseString = myString.ToTitleCase(); // Called as if it were a regular string method // titleCaseString now contains "Hello World"