Saturday, July 26, 2014

Hidden Secrets of Interfaces in .NET C#

Interface contains definitions for a group of related functionalties that a class or a struct can implement. Interface in C# is similar to an abstract class in which all methods are abstract (Why C# interface methods not declared as abstract). 

Interface can contain methods, properties, events, indexers but it can't contain constants, fields (why interface can't have fields), operators, instance constructors or types. Interface members are automatically public and cannot be static. (interfaces in MSDN)

When a class or struct implements an interface, it must provide an implementation for all the members that interface defines. If you implement an interface method in a deriving class it must be public. When a base list contains base class and interfaces, base class must come first in the list. 

Methods in interfaces can have optional parameters. But they are not enforced in implementing classes

Any class or struct that implements IEquatable<T> interface must contain definition for an Equals method. Also note that Reference types doesn't benefit much when using IEquatable.

Importance of an interface
Covered in SO, SO, Here 

An interface can inherit from one or more base interfaces. See Composition over Inheritance.

Explicit interface implementation 

Problem : Class implements 2 interfaces has a member with same signature
Solution : Explicit interface implementation



This can be used for cases where 2 interfaces each declare different members of the same name


IDisposable interface is used to release unmanaged resources. Use Dispose method of this interface to explicitly release unmanaged resources with garbage collector.

It's always nice to have a comparison between Interfaces and Abstract classes
Stackoverflow, Stackoverflow2, What does it mean to 'program to an interface', When to create an interface, Test if object implements interface and many more from stackoverflow

interfaces in C#
stackoverflow1, stackoverflow2, dreamincode


IEnumberable and IEnumerator 
Whats the difference (stackoverflow)
http://stackoverflow.com/questions/6802573/c-sharp-interfaces-whats-the-point
http://www.dotnetperls.com/interface 


0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook