32.5 C
New York
Thursday, June 20, 2024

When to make use of an summary class vs. interface in C#


When designing functions, it is very important know when to make use of an summary class and when to make use of an interface. Though summary courses and interfaces appear related in some methods, there are key variations that can decide which is your best option for what you’re attempting to perform. On this weblog publish I’ll talk about these variations and how you can resolve when to make use of which.

The brief reply: An summary class means that you can create performance that subclasses can implement or override. An interface solely means that you can outline performance, not implement it. And whereas a category can lengthen just one summary class, it will probably make the most of a number of interfaces. 

C# summary class defined

An summary class is a particular sort of sophistication that can not be instantiated. An summary class is designed to be inherited by subclasses that both implement or override its strategies. In different phrases, summary courses are both partially carried out or not carried out in any respect. You possibly can have performance in your summary class—the strategies in an summary class may be each summary and concrete. An summary class can have constructors—that is one main distinction between an summary class and an interface. You possibly can make the most of summary courses to design parts and specify some stage of widespread performance that have to be carried out by derived courses.

C# interface defined

An interface is mainly a contract—it doesn’t have any implementation. An interface can include solely methodology declarations; it can not include methodology definitions. Nor can you’ve gotten any member knowledge in an interface. Whereas an summary class could include methodology definitions, fields, and constructors, an interface could solely have declarations of occasions, strategies, and properties. Strategies declared in an interface have to be carried out by the courses that implement the interface. Be aware {that a} class can implement a couple of interface however lengthen just one class. The category that implements the interface ought to implement all its members. Like an summary class, an interface can’t be instantiated.

Key similarities between summary courses and interfaces in C#

There are 4 key similarities between interfaces and summary courses.

Conduct with out implementation: The C# programming language offers each interfaces and summary courses to outline conduct with out implementation. You possibly can make the most of an interface or an summary class to outline a contract that have to be adopted by varieties that stretch or implement that interface or summary class. For instance, you may outline strategies, properties, and occasions in an interface or an summary class that have to be carried out by varieties that stretch it. Nonetheless, from C# 8.0 onward, an interface can include default implementations for its members, i.e. strategies and properties.

No instantiation: You should use each summary courses and interfaces to outline varieties that can not be instantiated. As a substitute, you will need to implement an interface or lengthen an summary class by different varieties.

Help for polymorphism: You possibly can obtain polymorphism utilizing each interface and summary courses. Most significantly, you may have a derived class lengthen an summary base class and implement a number of interfaces.

Entry modifiers: Strategies in each interfaces and summary courses can embody entry modifiers. Nonetheless, it must be famous that from C# 7.2, all members in an interface are public by default.

Key variations between summary courses and interfaces in C#

Whereas there are specific similarities between interfaces and summary courses, there are additionally refined variations.

Default implementations: You possibly can have strategies in an summary class which have default implementations. Nonetheless, interfaces didn’t assist default implementations for its members till just lately. With C# 8.0, you may have default implementations for the members of an interface, much like summary courses.

Member varieties: In an summary class, you may have a number of member varieties reminiscent of fields, constructors, destructors, and static members. You can also have constructors in an summary class, however you can not have constructors in an interface. To outline a destructor in any class in C#, you prefix the title of the destructor with a tilde (~) signal.

State: Furthermore, summary courses can have state data, i.e., they’ll have fields. Nonetheless, you can not have occasion fields in interfaces. Because of this you may serialize an summary class however you may by no means serialize an interface. As a result of you may serialize solely a category, a struct, an enum, or a delegate. Whenever you serialize an summary class, it’s the occasion of the derived class that extends the summary class that’s really serialized.

Inheritance: Though a category can lengthen solely a single summary class, it will probably implement a number of interfaces. By implementing a number of interfaces, you may simulate a number of inheritance by leveraging interfaces in C#.

Benefits of utilizing summary courses as a substitute of interfaces in sure eventualities

Summary courses present structural, behavioral, and design capabilities that make them a good selection in sure eventualities.

State administration: You should use summary courses to take care of state data that the derived courses can entry.

Entry modifiers: You should use summary courses with entry modifiers that present fine-grained management over its members.

Constructors and destructors: You possibly can have constructors and destructors in an summary class, permitting you to initialize its members and write code for cleanup logic. Thus you may initialize the members of the summary class when an occasion of any of its derived courses is created and retrieve reminiscence assets when these situations are destroyed.

Benefits of utilizing interfaces as a substitute of summary courses in sure eventualities

There are additionally sure benefits of utilizing interfaces as a substitute of summary courses.

A number of implementations: Interfaces are most well-liked over summary courses whenever you want to set up contracts in your utility with out implementing a direct lineage. A category can implement a number of interfaces, permitting it to evolve to quite a few contracts concurrently. This can assist you create parts that make the most of cross-cutting considerations in an utility.

Modularity: Interfaces foster a design wherein you outline a contract that any implementing class should adhere to, thereby selling a modular, extensible, and versatile structure that makes your code simpler to check, lengthen, and keep.

Mocking: You should use interfaces to create mock objects when writing your unit checks. As a result of you may outline conduct with out implementation in an interface, you should utilize interfaces to create unit checks that don’t rely on implementations outlined in concrete courses.

Design flexibility: You possibly can make the most of interfaces to create functions with evolving designs by leveraging the default implementation characteristic launched in C# 8.0. Therefore, you should utilize interfaces to create functions which are versatile and evolving with out breaking present implementations. By programming to an interface as a substitute of its implementations, you may work with abstractions in lieu of concrete courses. This fosters a design wherein parts are interchangeable so long as they adhere to the identical contract outlined by the interface that they implement.

Ought to I take advantage of an summary class or an interface?

Summary courses present you the pliability to have sure concrete strategies and another strategies that the derived courses ought to implement. Against this, if you happen to use interfaces, you would want to implement all of the strategies within the class that extends the interface. An summary class is an effective alternative when you have plans for future enlargement – i.e. if a future enlargement is probably going within the class hierarchy. If you need to offer assist for future enlargement when utilizing interfaces, you’ll want to increase the interface and create a brand new one.

On a special notice, it’s simple so as to add a brand new interface to the hierarchy if want be. Nonetheless, if you have already got an summary class in your hierarchy, you may’t add one other—i.e., you may add an summary class provided that none can be found. It’s best to use an interface if you would like a contract on some conduct or performance. You shouldn’t use an interface if it’s worthwhile to write the identical code for the interface strategies. On this case, it’s best to use an summary class, outline the tactic as soon as, and reuse it as wanted. Do use interfaces to decouple your utility’s code from particular implementations of it, or to limit entry to members of a sure sort.

As Microsoft’s documentation of interfaces states:

By utilizing interfaces, you may, for instance, embody conduct from a number of sources in a category. That functionality is vital in C# as a result of the language doesn’t assist a number of inheritance of courses. As well as, you will need to use an interface if you wish to simulate inheritance for structs, as a result of they’ll’t really inherit from one other struct or class.

Implicit and specific interface implementations

Interfaces may be carried out implicitly or explicitly. Let me clarify how these two implementations differ. Contemplate an interface known as IBusinessLogic.

public interface IBusinessLogic
{
   void Initialize();
}

The next class named BusinessLogic implements the IBusinessLogic interface.

public class BusinessLogic : IBusinessLogic
{
   public void Initialize()
   {
       //Some code
   }
}

You possibly can create an occasion of the BusinessLogic class explicitly after which name the Initialize() methodology as proven beneath.

 IBusinessLogic businessLogic = new BusinessLogic();
businessLogic.Initialize();

The next code snippet illustrates how one can implement the IBusinessLogic interface implicitly.

public class BusinessLogic : IBusinessLogic
{
   void IBusinessLogic.Initialize()
   {
   }
}

Now you can invoke the Initialize() methodology the identical method utilizing a reference to the IBusinessLogic interface. The distinction within the two approaches is that whenever you implement the interface explicitly in your class, you’re constrained to invoking a way of your interface utilizing a reference to the interface solely. Subsequently the next code snippet wouldn’t work, i.e. wouldn’t compile.

 BusinessLogic businessLogic = new BusinessLogic();
businessLogic.Initialize();

Summary courses vs. interfaces in C# FAQs

What’s the basic distinction between an summary class and an interface?

Though interfaces in C# can have solely properties, summary courses in C# could have properties and fields. Usually, we use summary courses to create an summary base class that different courses can lengthen. Alternatively, interfaces are carried out by courses to evolve to a contract.

With C# 8.0, an interface can have static, digital, summary, sealed, personal, and extern members. Nonetheless, an interface can not have constructors or destructors in any variations of the C# programming language.

Can a category inherit from a number of interfaces or summary courses?

A category in C# can implement a number of interfaces, however it will probably inherit from one and just one summary class.

When ought to I take advantage of an summary class over an interface?

We must always use an summary class when we have to outline state data and specify how the fields must be initialized.

Can an summary class or an interface include fields?

An summary class can include fields however you can not have fields in an interface. This explains why you can not serialize an interface in C#.

How do default implementations in C# 8.0 have an effect on the distinction between summary courses and interfaces?

With the introduction of C# 8.0, interfaces can have default implementations for his or her members. Nonetheless, they nonetheless can not have constructors or fields. And in contrast to the strategies of an summary class, the default implementations of interfaces can not entry personal fields.

How do summary courses and interfaces in C# differ in efficiency?

The efficiency distinction between interfaces and summary courses depends upon the implementation. You possibly can have a number of member definitions in an summary class or an interface. It’s also possible to make your interface or summary class light-weight by having solely member declarations. Nonetheless, as a result of summary courses can have constructors and digital strategies, they have an inclination to require extra reminiscence and CPU assets than interfaces.

In different phrases, you incur a slight efficiency penalty when utilizing summary courses. Microsoft recommends utilizing concrete varieties at any time when potential for higher efficiency.

Copyright © 2024 IDG Communications, Inc.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles