0% found this document useful (0 votes)
5 views21 pages

Understanding Interfaces in C#

Uploaded by

dalewilson02718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views21 pages

Understanding Interfaces in C#

Uploaded by

dalewilson02718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interfaces

What is an Interface in C#?


The Interface in C# is a Fully Unimplemented Class used for declaring a set of
operations/methods of an object. So, we can define an interface as a pure abstract class,
which allows us to define only abstract methods. The abstract method means a method
without a body or implementation. It is used to achieve multiple inheritances, which the
class can’t achieve. It is used to achieve full abstraction because it cannot have a method
body.
Differences Between Concrete Class, Abstract Class, and
Interface in C#
1. Class: Contains only the Non-Abstract Methods (Methods with Method Body).
2. Abstract Class: Contains both Non-Abstract Methods (Methods with Method Body) and
Abstract Methods (Methods without Method Body).
3. Interface: Contain only Abstract Methods (Methods without Method Body).

The default access modifier of members in Class and Interfaces


the default in interfaces is public , which in class is private .
you will get a compiler error if child method is private

The Ways that you can implement methods of the interfaces :


First , normal implementation using public access specifier .
Second , explicit implementation using interface name .
If the method is implemented using the public access specifier, then you can create the object
and call it directly. But if the method is implemented using the interface name, then while calling
the method, we need to typecast the object to the interface type, or you can create an interface
reference and call the method. So, in our case, we call the Add method directly using obj1, but
while calling the Sub method, we need to type case the obj1 to Interface2 type as this is an
instance of Implementation Class, or you can call directly using reference variable obj2 as
shown in the below image.
When to use Interface in C#?
Interfaces in C# are a powerful feature that defines contracts or specifications that classes must
adhere to. You should consider using interfaces in the following scenarios:

Defining a Common Contract: To ensure that multiple classes provide a common set of
methods, properties, events, or indexers, you can create an interface to define that
contract. This is useful in situations where different classes need to exhibit similar behavior
but may have different implementations.
Implementing Multiple Inheritance: C# does not support multiple inheritance for classes
(a class cannot inherit from multiple classes) but supports multiple interface
implementation. If you need a class to inherit behavior or structure from multiple sources,
you can use interfaces to achieve this. This allows you to share code among different
classes without the complexities of multiple-class inheritance.
Enforcing a Specific Structure: When you want to enforce a specific structure or a
particular set of methods and properties for classes within your application or library,
interfaces can help ensure that classes conform to that structure.
Implementing Polymorphism: Interfaces are essential for achieving polymorphism in C#.
When different classes implement the same interface, you can treat objects of these
classes uniformly, making it easier to work with various objects in a polymorphic way. This
is useful in scenarios where you want to work with objects at a higher level of abstraction.
Testing and Mocking: Interfaces are valuable in unit testing scenarios. You can create
interfaces for external dependencies or services and then create mock implementations of
those interfaces for testing purposes. This enables you to isolate and test individual
components of your codebase more effectively.
Collaboration in Teams: Interfaces can help teams collaborate more effectively on large
codebases. By defining clear interfaces, developers can work independently on different
parts of a project, knowing that their code will integrate seamlessly as long as it adheres to
the specified interfaces.
Code Reusability: Interfaces promote code reusability. You can create a set of interfaces
representing common functionalities in your application, and different classes can
implement these interfaces. This way, you can reuse code across multiple classes without
duplicating it.
Dependency Injection: When using dependency injection, interfaces often define
dependencies that can be injected into classes. This helps achieve loose coupling and
makes it easier to switch implementations at runtime

What is the Interface (interview Question )?


The Interface in C# is a fully un-implemented class used for declaring a set of methods
of an object. So, we can define an interface as a pure abstract class which allows us to
define only abstract methods. The abstract method means a method without a body or
implementation.
It is used to achieve multiple inheritances which can’t be achieved by class. It is used to
achieve full abstraction because it cannot have a method body.
Its implementation must be provided by class or struct. The class or struct which
implements the interface must provide the implementation of all the methods declared
inside the interface.

What are the different types of Inheritance Supported by C#?


A class can be inherited either from another class or from an interface also. So, inheritance can
be divided into two categories

1. Implementation Inheritance
2. Interface Inheritance
Why do we need an interface in C#?
We know the concept of multiple inheritances where one class is derived from more than one
superclass. For example, a definition like

But this concept is not supported by .NET with classes. Since a large no of real-time
applications require the use of multiple inheritances, where we inherit properties and behaviors
from several different classes. That’s why .NET provides an alternative approach known as the
interface to support the concept of multiple inheritances.

Can I use public access specifiers for interface methods in C#?


.NET interface methods are implicitly public by default, even if they belong to nested interfaces.
Non-public modifiers are not valid for interface methods. So, the compiler will fail and warn you
in this case. Nested interfaces may be declared protected or private but not the interface
methods. So, if you try to declare the method will public access specifier, you will get the
following error.

Can an Interface Implement an Abstract Class in C#?


No. In .NET an interface cannot implement an abstract class. An interface may only extend a
super interface. However, an abstract class can implement an interface because an abstract
class can contain both abstract methods and concrete methods.

Can an Interface be Declared as Sealed in C#?


No, it is not permitted to declare an interface as sealed; it will cause a compilation error. This is
a .NET language design decision. Interface types are intended to be implemented and can be
extended without restriction. If you try to declare the interface as sealed, you will get the
following error.

Is more than one Interface allowed to Implement a Class in C#?


Yes, a class can implement multiple interfaces; this is an effective way to achieve multiple
inheritances in C#. But a class can extend only one superclass. For a better understanding,
please have a look at the following example.

![[Pasted image [Link]]]

Is it Necessary to Implement all Interface Methods in C#?


It is not necessary for a class that implements an interface to implement all its methods, but in
this case, the class must be declared as abstract. For a better understanding, please have a
look at the following code.

How Interface is Different from a Class in C#?


An interface is different from a class in the following ways:

1. We cannot instantiate an interface.


2. An interface does not contain any constructor or data fields or destructor, etc.
3. All of the methods of an interface are abstract and public by default.
4. An interface is not extended by a class; it is implemented by a class.
5. An interface can extend multiple interfaces.

What are the Similarities Between the Interface and Abstract


Class in C#?
An interface is similar to an abstract class in the following ways

1. Both interface and the abstract class cannot be instantiated means we cannot create the
object.
2. But we can create a reference variable for both the interface and abstract class.
3. The subclass should implement all abstract methods.
4. Both cannot be declared sealed.

What is the Difference Between Interface and Abstract Class in


C#?
The main difference to be answered in the interview is as follows. The interface is a fully un-
implemented class used for declaring a set of methods of an object. The abstract class is
a partially implemented class. It implements some of the methods of an object. These
implemented methods are common for all next-level subclasses. The remaining operations are
implemented by the next-level subclasses according to their requirement.

The interface allows us to develop multiple inheritances. So, we must start object design with
interface whereas abstract class does not support multiple inheritances so it always comes next
to interface in the object creation process.

Abstract Class:

1. It is a partially implemented class. It allows us to define both concrete and abstract


methods.
2. It should be declared as abstract by using the abstract keyword, abstract methods should
also contain the abstract keyword.
3. Its member’s default accessibility modifier is private and can be changed to any of the
other accessibility modifiers.
4. It is possible to declare data fields in an abstract class.
5. An abstract class can contain a non-abstract function.
6. An abstract class can inherit from another abstract class or from an interface.
7. An abstract class cannot be used to implement multiple inheritances.
8. Abstract class members can have Access Specifiers.

Interface:

1. It is a fully un-implemented class. It allows us to define only abstract methods.


2. It should be created by using the keyword interface. By default, all the members are
abstract only. Explicitly using abstract keyword is not allowed.
3. Its member’s default accessibility modifier is public and cannot be changed.
4. It is not possible to declare any data fields in an interface.
5. An interface cannot contain non-abstract functions.
6. An interface can inherit from only other interfaces but cannot inherits from the abstract
class.
7. An interface can be used to implement multiple inheritances.
8. Interface members cannot have Access Specifiers.

What are the Advantages of using Interface in C#?


The following are the advantages of using Interface in the C# application.

1. It is used to achieve loose coupling.


2. It is used to achieve total abstraction.
3. To achieve multiple inheritance and abstraction.

What are the types of Inheritance ?


Why Multiple Inheritance Not Supported Through Classes in
C#?
The interfaces don't have the ambiguity problem with
inheritance ?
When do you choose interface over an abstract class or vice
versa in C#?
If we want some implementation that will be the same for all the derived classes, then it is better
to go for an abstract class instead of an interface.

Can you create an instance of an interface in C#?


No, you cannot create an instance of an interface in C#. But you can create a reference
variable of an interface.

If a class inherits an interface, what are the 2 options available


for that class?
Option 1: Provide Implementation for all the members inherited from the interface. For a better
understanding, please have a look at the following example.

Option 2: If the class does not wish to provide Implementation for all the members inherited
from the interface, then the class has to be marked as abstract and also needs to declare the
unimplemented interface methods as abstract. For a better understanding, please have a look
at the following example.

A class inherits from 2 interfaces and both interfaces have the


same method name as shown below. How should the class
implement the drive method for both Car and Bus interfaces?
By using explicitly Interface Implementation. To implement the Drive() method use the fully
qualified name as shown in the example below. To call the respective interface drive method
typecast the demo object to the respective interface and then call the drive method.
Abstract Classes and Abstract methods
What are Abstract Methods in C#?
In C#, abstract methods are methods declared within an abstract class or an interface that
do not have a method body or implementation in the declaring class or interface.
A method without the body is known as the Abstract Method. What the method contains is
only the declaration of the method. That means the abstract method contains only the
declaration, no implementation. The following method is a non-abstract method as this
method contains a body.
But remember, if you want to make any method an abstract method, then you should
explicitly use the abstract modifier as follows. And once you use the abstract modifier,
automatically, the method will be called an abstract method. public abstract void Add(
num1, num2);

What are Abstract Classes in C#?


In C#, an abstract class is a class that serves as a blueprint for other classes. Abstract
classes cannot be instantiated directly, but they can be used as base classes for other
classes that derive from them. Abstract classes are declared using the abstract keyword.
They often define a common set of characteristics or behaviors that should be shared
among multiple derived classes.
when a class contains any abstract methods, it must and should be declared using the
abstract modifier, and when a class is created using an abstract modifier, it is called an
Abstract class in C#.
We cannot define the abstract methods directly anywhere. We need to define the abstract
method inside an abstract class only.

What is the use of the Abstract Method in C#?


If a method is declared abstract under any class, then the child class of that abstract class
is responsible for implementing the abstract method without fail.

Is Abstract Class Containing Only Abstract Methods in C#?


Don’t think an abstract class can contain only abstract methods. It can also contain non-
abstract methods. You need to remember that if a class is non-abstract, it contains only
non-abstract methods, but if a class is abstract, it contains both abstract and non-abstract
methods in C#.

Who will Provide the Implementation of Abstract Methods in C#?


The Answer is Child Class. If you have a child class of an abstract class, then it is the
responsibility of the child class to provide the implementation for all the abstract methods
of the parent class. You cannot escape. Every method should be implemented. If you
implement all the abstract methods, you can only consume the non-abstract method of the
Parent class.

Can we create an instance of an abstract class in C#?


No. We cannot create an instance of an abstract class. Whether the abstract class
contains any abstract methods or not, creating an instance of the abstract class is
impossible. If you try, you will get a compile-time error

Why Abstract Class Cannot Be Instantiated in C#?


Its abstract methods cannot be executed because it is not a fully implemented class. If the
compiler allows us to create the object for an abstract class, we can invoke the abstract method
using that object, which CLR cannot execute at runtime. Hence, to restrict calling abstract
methods, the compiler does not allow us to instantiate an abstract class.

Can we Create a Reference for the Abstract Class in C#?


Yes, we can create a reference for the abstract class in C#. But we cannot create an instance of
an abstract class in C#

You need to remember that parent class references, even if created using child class instances,
cannot be called child class methods, provided the methods are defined in the child class.
Overridden methods are not pure child-class methods, so the parent class references can also
call the child class overridden members but cannot call the pure child class members.

If an abstract class has an implementation of an abstract


method does child class require to override it ?
Abstract Method (No Implementation): If the abstract class declares an abstract method
(without any implementation), then any non-abstract subclass must provide an
implementation for that method.
Abstract Method with Implementation: Once an abstract method is given an
implementation in the abstract class, it ceases to be abstract, and any subclass is not
required to implement it. However, the subclass may still override it if necessary.
Regular Method: A regular (non-abstract) method in the abstract class, regardless of
whether it was abstract before, can be inherited by child classes without the need for the
child class to override it.

When to use Abstract classes and Methods in C#?


You should consider using abstract classes and methods in C# when you want to:

Define a Common Base: Abstract classes are useful when defining a common base for a
group of related classes. If you have several classes with common properties, methods, or
behavior, you can create an abstract base class to avoid duplicating code.
Enforce a Contract: Abstract methods within abstract classes (or interfaces) allow you to
enforce a contract that derived classes must adhere to. Abstract methods define a set of
methods for which derived classes must provide concrete implementations, ensuring that
certain functionality is available.
Provide Default Implementations: Abstract classes can include both abstract and
concrete members. You can provide default implementations in the abstract class that
derived classes can choose to override or extend. This allows you to offer a common
implementation while still allowing flexibility for customization.
Implement Polymorphism: Abstract classes and methods are fundamental to achieving
object-oriented programming polymorphism. You can create a collection of objects of
different derived classes but treat them uniformly through the abstract base class or
interface.
Create Frameworks and Libraries: Abstract classes are often used to create
frameworks, libraries, or APIs. By defining an abstract class with abstract methods, you
specify a contract the client code must implement to use your framework effectively.
Extend Functionality: Abstract classes allow you to extend functionality in a modular way.
When adding new features or capabilities to a class hierarchy, you can create a new
derived class from the abstract base class, implementing the necessary abstract methods.
Ensure Code Consistency: Abstract methods enforce a consistent structure in derived
classes. This can be especially useful in large development teams or projects requiring
multiple developers to follow a common coding standard.
Enable Code Reusability: By providing a common base class with shared functionality
and structure, you promote code reusability. Code in the abstract base class can be used
across multiple derived classes, reducing redundancy and maintenance efforts.
Support Extension Points: Abstract methods in abstract classes act as extension points.
They define areas where derived classes can add custom logic without modifying the core
functionality of the base class.
Implement Template Method Pattern: Abstract classes often play a role in implementing
the Template Method design pattern. In this pattern, the abstract class defines the skeleton
of an algorithm with certain steps marked as abstract methods, and derived classes
provide specific implementations for those steps.

Why should the method have an abstract keyword if it does not


have a body in C#?
In a class, we are allowed only to define a method with the body. Since we are changing its
default behavior (which means removing its body) it must have the abstract keyword in its
prototype.

When Should a Class be Declared as Abstract in C#?


A class should be declared as abstract in C# in the following 3 cases.
Case1 :

![[Pasted image [Link]]]

Case2 :

![[Pasted image [Link]]]

Case3 :

![[Pasted image [Link]]]

When to use the Abstract Method in C#?


Abstract methods are usually declared where two or more subclasses are expected to fulfill a
similar role in a different manner. You can also do the same thing using an interface also. But if
we are using an abstract class means we can provide some common functionality that is going
to be the same for all the child classes and this is not possible using the interface.

What type of member can we define in an abstract class?


We can define all static and non-static members including properties, fields, indexes, and also
abstract methods.

How can we execute static and non-static concrete members of


the abstract class?
Static members can be executed directly by using the class name and its non-static members
are executed by using its concrete sub-class or child class object. For a better understanding,
please have a look at the following example.

Can we Declare an Abstract Method as Static in C#?


No, we are not allowed to declare an abstract method as static. It leads to Compile Time Error.
If the compiler allows us to declare it as static, it can be invoked directly using the class name
which cannot be executed by CLR at runtime. Hence to restrict calling abstract methods
compiler does not allow us to declare an abstract method as static.

Can we Declare an Abstract Method as Sealed in C#?


No, because it should be allowed to override in subclasses. If we will try to use sealed then we
will get a Compile Time Error .

Can we Declare an Abstract Method as Private in C#?


No, because it should be inherited by subclasses. It leads to Compile Time Error: virtual or
abstract members cannot be private.

Can we Declare a Concrete Class as Abstract in C#?


Yes, it is allowed. We can define an abstract class with only non-abstract methods. Defining a
class as abstract is a way of preventing someone from instantiating a class that is supposed to
be extended first. To ensure our class non-static members are only accessible via sub-class
objects we should declare the concrete class as abstract.

What is the difference between abstract methods and virtual


methods ?

Definition:

Virtual Methods:
Can be declared in any class (regular or abstract).
The containing class does not need to be abstract.
The method can have an implementation in the base class.
Abstract Methods:
Must be declared in an abstract class.
The containing class must be abstract.
The method cannot have any implementation in the base class; it only serves as a
contract that derived classes must implement.
Overriding:

Virtual Methods:
Overriding is optional in derived classes.
If not overridden, the base class implementation is used.
Abstract Methods:
Overriding is mandatory in derived classes.
Derived classes must provide an implementation for the abstract method.

Instantiation:

Virtual Methods:
The base class can be instantiated if it only contains virtual methods.
Abstract Methods:
The base class cannot be instantiated directly if it contains abstract methods.

You might also like