What are extension methods in C#?
Answer
Extension methods allow adding methods to existing types without modifying them — even sealed classes or types from external libraries. They are defined as static methods in a static class, with the first parameter prefixed with this indicating the type being extended. Example: public static class StringExtensions { public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); }. Usage: "hello".IsNullOrEmpty() — called as if it were an instance method. LINQ methods (Where, Select, OrderBy) are all extension methods on IEnumerable<T>. Rules: (1) Extension methods cannot access private members. (2) Instance methods always take precedence over extension methods with the same signature. (3) The namespace containing the extension class must be imported. Extension methods are syntactic sugar — the compiler translates them to static method calls.
Previous
What is the difference between == and .Equals() in C#?
Next
What is a lambda expression in C#?