In C#, interfaces define a contract that classes can implement, specifying a set of methods, properties, and events that the implementing classes must provide. Here’s a list of 50 common interfaces in C# along with brief explanations and common methods for each, along with code snippet examples for some of them:
- IEnumerable:
- Method:
GetEnumerator() - Explanation: Provides a way to iterate through a collection.
IEnumerable<int> numbers = new List<int> { 1, 2, 3 };
foreach (var number in numbers) { /* ... */ }
- IComparable:
- Method:
CompareTo(object obj) - Explanation: Allows objects to be compared to determine their ordering.
public class MyClass : IComparable<MyClass> { /* ... */ }
- IEquatable:
- Method:
Equals(T other) - Explanation: Ensures objects can be compared for equality.
public class MyClass : IEquatable<MyClass> { /* ... */ }
- IDisposable:
- Method:
Dispose() - Explanation: Provides a way to release unmanaged resources.
public class MyDisposable : IDisposable { /* ... */ }
- IList:
- Methods:
Add,Remove,IndexOf,Insert,Count,Clear,Contains,CopyTo - Explanation: Represents a non-generic collection of objects.
IList<int> numbers = new List<int>();
numbers.Add(42);
- IDictionary:
- Methods:
Add,Remove,TryGetValue,ContainsKey,ContainsValue,Keys,Values - Explanation: Represents a collection of key-value pairs.
IDictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("One", 1);
- INotifyPropertyChanged:
- Method:
PropertyChanged - Explanation: Notifies clients that a property value has changed.
public class MyViewModel : INotifyPropertyChanged { /* ... */ }
- IEnumerable:
- Method:
GetEnumerator() - Explanation: Represents a strongly-typed collection of objects.
IEnumerable<int> numbers = new List<int> { 1, 2, 3 };
foreach (var number in numbers) { /* ... */ }
- IQueryable:
- Methods: Various LINQ methods
- Explanation: Enables LINQ query operations on data sources.
IQueryable<string> query = dataSource.Where(item => item.Length > 5);
- IComparable:
- Method:
CompareTo(T other) - Explanation: Allows strongly-typed comparison of objects.
public class MyClass : IComparable<MyClass> { /* ... */ } - Method:
- IEquatable:
- Method:
Equals(T other) - Explanation: Ensures strongly-typed equality comparison.
public class MyClass : IEquatable<MyClass> { /* ... */ } - Method:
- IList:
- Methods:
Add,Remove,IndexOf,Insert,Count,Clear,Contains,CopyTo - Explanation: Represents a generic list of objects.
IList<int> numbers = new List<int>(); numbers.Add(42); - Methods:
- IDictionary:
- Methods:
Add,Remove,TryGetValue,ContainsKey,ContainsValue,Keys,Values - Explanation: Represents a generic collection of key-value pairs.
IDictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("One", 1); - Methods:
- IFormattable:
- Method:
ToString(string format, IFormatProvider formatProvider) - Explanation: Provides a mechanism for formatting objects as strings.
public class MyData : IFormattable { /* ... */ } - Method:
- ICloneable:
- Method:
Clone() - Explanation: Allows an object to create a shallow copy of itself.
public class MyCloneable : ICloneable { /* ... */ } - Method:
- IConvertible:
- Methods: Various conversion methods
- Explanation: Provides methods to convert an object to a different data type.
int value = Convert.ToInt32("42"); - IAsyncResult:
- Methods:
AsyncWaitHandle,CompletedSynchronously,IsCompleted - Explanation: Represents the status of an asynchronous operation.
IAsyncResult asyncResult = SomeAsyncMethod.BeginInvoke(callback, state); - Methods:
- ICustomFormatter:
- Method:
Format(string format, object arg, IFormatProvider formatProvider) - Explanation: Custom string formatting.
public class MyFormatter : ICustomFormatter { /* ... */ } - Method:
- IEqualityComparer:
- Methods:
Equals,GetHashCode - Explanation: Compares objects for equality.
IEqualityComparer<string> comparer = StringComparer.OrdinalIgnoreCase; - Methods:
- IComparer:
- Method:
Compare - Explanation: Compares two objects for ordering.
IComparer<int> comparer = Comparer<int>.Default; - Method:
- IAsyncResult:
- Methods:
AsyncWaitHandle,CompletedSynchronously,IsCompleted - Explanation: Represents the status of an asynchronous operation.
IAsyncResult asyncResult = SomeAsyncMethod.BeginInvoke(callback, state); - Methods:
- IConvertible:
- Methods: Various conversion methods
- Explanation: Provides methods to convert an object to a different data type.
int value = Convert.ToInt32("42"); - ISerializable:
- Methods:
GetObjectData - Explanation: Provides control over object serialization.
[Serializable] public class MySerializable : ISerializable { /* ... */ } - Methods:
- IComparable:
- Method:
CompareTo(T other) - Explanation: Allows strongly-typed comparison of objects.
public class MyClass : IComparable<MyClass> { /* ... */ } - Method:
- IList:
- Methods:
Add,Remove,IndexOf,Insert,
Count,Clear,Contains,CopyTo- Explanation: Represents a generic list of objects.
IList<int> numbers = new List<int>(); numbers.Add(42); - Methods:
- IDictionary:
- Methods:
Add,Remove,TryGetValue,ContainsKey,ContainsValue,Keys,Values - Explanation: Represents a generic collection of key-value pairs.
IDictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("One", 1); - Methods:
- IFormattable:
- Method:
ToString(string format, IFormatProvider formatProvider) - Explanation: Provides a mechanism for formatting objects as strings.
public class MyData : IFormattable { /* ... */ } - Method:
- IComparable:
- Method:
CompareTo(object obj) - Explanation: Allows objects to be compared to determine their ordering.
public class MyClass : IComparable<MyClass> { /* ... */ } - Method:
- IEquatable:
- Method:
Equals(T other) - Explanation: Ensures objects can be compared for equality.
public class MyClass : IEquatable<MyClass> { /* ... */ } - Method:
- IDisposable:
- Method:
Dispose() - Explanation: Provides a way to release unmanaged resources.
public class MyDisposable : IDisposable { /* ... */ } - Method:
- ISerializable:
- Methods:
GetObjectData - Explanation: Provides control over object serialization.
[Serializable] public class MySerializable : ISerializable { /* ... */ } - Methods:
- IComparer:
- Method:
Compare - Explanation: Compares two objects for ordering.
IComparer<int> comparer = Comparer<int>.Default; - Method:
- IEqualityComparer:
- Methods:
Equals,GetHashCode - Explanation: Compares objects for equality.
IEqualityComparer<string> comparer = StringComparer.OrdinalIgnoreCase; - Methods:
- IAsyncDisposable (C# 8.0 and later):
- Method:
DisposeAsync() - Explanation: Provides asynchronous disposal of resources.
public class MyAsyncDisposable : IAsyncDisposable { /* ... */ } - Method:
- INotifyPropertyChanged:
- Method:
PropertyChanged - Explanation: Notifies clients that a property value has changed.
public class MyViewModel : INotifyPropertyChanged { /* ... */ } - Method:
- IProgress:
- Method:
Report(T value) - Explanation: Reports progress updates during an asynchronous operation.
async Task SomeAsyncOperation(IProgress<int> progress) { // Report progress: progress.Report(50); } - Method:
- IHttpHandler:
- Method:
ProcessRequest(HttpContext context) - Explanation: Represents an HTTP handler.
public class MyHandler : IHttpHandler { /* ... */ } - Method:
- IHttpModule:
- Methods:
Init(HttpApplication context),Dispose() - Explanation: Represents an HTTP module.
public class MyModule : IHttpModule { /* ... */ } - Methods:
- IWebHostBuilder (ASP.NET Core):
- Methods: Various methods for configuring a web host.
- Explanation: Provides a builder pattern for configuring and building an ASP.NET Core web host.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); - IConfiguration (ASP.NET Core):
- Methods: Various methods for accessing configuration values.
- Explanation: Provides access to application configuration settings.
IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); - IApplicationBuilder (ASP.NET Core):
- Methods: Various methods for configuring the application’s request pipeline.
- Explanation: Used to configure the middleware pipeline in ASP.NET Core applications.
public void Configure(IApplicationBuilder app) { app.UseMiddleware<CustomMiddleware>(); } - IServiceCollection (ASP.NET Core):
- Methods:
AddTransient,AddScoped,AddSingleton, and more for configuring services. - Explanation: Used for registering and configuring services in ASP.NET Core applications.
public void ConfigureServices(IServiceCollection services) { services.AddTransient<IMyService, MyService>(); } - Methods:
- IRouteBuilder (ASP.NET Core):
- Methods: Various methods for defining routes.
- Explanation: Used to configure routing in ASP.NET Core applications.
public void Configure(IRouteBuilder routes) { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); } - IActionResult (ASP.NET Core):
- Method:
ExecuteResultAsync(ActionContext context) - Explanation: Represents the result of an MVC action method.
public class MyController : Controller { public IActionResult Index() { return View(); } } - Method:
- ILogger (ASP.NET Core):
- Methods: Various logging methods (
LogInformation,LogError, etc.). - Explanation: Used for logging in ASP.NET Core applications.
public class MyService { private readonly ILogger<MyService> _logger;public MyService(ILogger<MyService> logger) { _logger = logger; } public void DoWork() { _logger.LogInformation("Doing some work..."); }} - Methods: Various logging methods (
- IHostingEnvironment (ASP.NET Core):
- Methods:
IsDevelopment,IsStaging,IsProduction, etc. - Explanation: Provides information about the hosting environment in ASP.NET Core applications.
public class MyMiddleware { public MyMiddleware(IHostingEnvironment env) { if (env.IsDevelopment()) { // Do something in the development environment. } } } - Methods:
- IUrlHelper (ASP.NET Core):
- Methods: Various methods for generating URLs.
- Explanation: Used for generating URLs in ASP.NET Core applications.
csharp public IActionResult MyAction() { var url = Url.Action("Index", "Home"); // ... }
48.
IQueryable:
– Methods: Various LINQ methods
– Explanation: Enables LINQ query operations on data sources.csharp IQueryable<string> query = dataSource.Where(item => item.Length > 5);
- IAsyncEnumerable (C# 8.0 and later):
- Methods:
GetAsyncEnumerator()Explanation: Represents an asynchronous sequence of values.
IAsyncEnumerable<int> asyncSequence = GetAsyncData(); await foreach (var item in asyncSequence) { /* ... */ } - Methods:
- IAsyncEnumerator (C# 8.0 and later):
- Methods:
MoveNextAsync(),Current - Explanation: Provides asynchronous iteration over a sequence of values.
csharp IAsyncEnumerator<int> asyncEnumerator = GetAsyncData().GetAsyncEnumerator(); while (await asyncEnumerator.MoveNextAsync()) { var item = asyncEnumerator.Current; // ... }
- Methods:
