In C#, "extension" usually means extension methods: static methods that can be called as if they were instance methods of an existing type, without modifying that type, inheriting from it or recompiling it. Defining an extension method - Put it in a static class. - Make the method static. - Mark the first parameter with this to indicate the type being extended. public static class StringExtensions { public static bool IsValidEmail(this string? value) => !string.IsNullOrWhiteSpace(value) && MailAddress.TryCreate(value, out _); public static string Truncate(this string value, int maxLength) => value.Length <= maxLength ? value : value[..maxLength] + "…"; } Using it (after importing the namespace) string email = "asha@example.com"; bool ok = email.IsValidEmail(); // looks like an instance method string title = longTitle.Truncate(50); The compiler translates email.IsValidEmail() into StringExtensions.IsValidEmail(email). Where they are used - LINQ is entirely built on extension methods on IEnumerable<T> and IQueryable<T> (Where, Select, OrderBy). - ASP.NET Core configuration: builder.Services.AddDbContext(...), app.UseAuthentication(), MapControllers() — and the common practice of grouping your own registrations: public static class ServiceCollectionExtensions { public static IServiceCollection AddOrdersModule(this IServiceCollection services, IConfiguration config) { services.AddScoped<IOrderService, OrderService>(); services.Configure<OrderOptions>(config.GetSection("Orders")); return services; } } - Adding helpers to types you do not own (sealed framework classes, third-party libraries, interfaces). Rules and limitations - Instance methods win: if the type already has a method with the same signature, the extension method is never called. - Extension methods can only access public members; they cannot access private state. - They can be called on null references (the method receives null), so handle null explicitly. - Overuse can make code harder to discover; keep them focused and in clearly named namespaces. Newer C# versions (C# 14) also introduce extension members with "extension" blocks, which allow extension properties and static extension members, in addition to classic extension methods. The term can also mean other "extensions" in context (browser or Visual Studio extensions, file extensions), so clarify if the question is ambiguous — but in C# interviews it almost always means extension methods.
Ravindra Wadile · · 0 likes