Junior — Middle
What methods can be used to add functionality to an existing class in C# without modifying its source code?
sobes.tech AI
Answer from AI
In C#, to add functionality to an existing class without modifying its source code, you can use extension methods. These are static methods that appear as instance methods but are defined outside the class.
Example:
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
// Usage:
string s = null;
bool result = s.IsNullOrEmpty();
Thus, you can "add" methods to any classes even if you do not have access to their source code.