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

OOPS Interview

The document provides an overview of various programming concepts in C#, including keywords like Readonly, Const, Static ReadOnly, and class types such as Static, Sealed, and Abstract classes. It explains Object-Oriented Programming principles like inheritance, polymorphism, abstraction, and encapsulation, along with differences between concepts like Overloading and Overriding. Additionally, it covers constructors, the use of interfaces, and distinctions between various keywords and classes in C#.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views21 pages

OOPS Interview

The document provides an overview of various programming concepts in C#, including keywords like Readonly, Const, Static ReadOnly, and class types such as Static, Sealed, and Abstract classes. It explains Object-Oriented Programming principles like inheritance, polymorphism, abstraction, and encapsulation, along with differences between concepts like Overloading and Overriding. Additionally, it covers constructors, the use of interfaces, and distinctions between various keywords and classes in C#.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Readonly

Readonly is the keyword whose value we can change during runtime or we can
assign it at run time but only through the non-static constructor.

Const
Const is nothing but "constant", a variable of which the value is constant but at
compile time. And it's mandatory to assign a value to it. By default a const is static
and we cannot change the value of a const variable throughout the entire program.

Static ReadOnly
A Static Readonly type variable's value can be assigned at runtime or assigned at
compile time and changed at runtime. But this variable's value can only be changed
in the static constructor. And cannot be changed further. It can change only once at
runtime.
Static Class: Declared with Static keyword, methods in Static Class are also static along with
variables of the class.
This class cannot be instantiated, i.e we cannot have objects of this class. To access methods of this
class, you can directly use classname.method. Also this class cannot be inherited.
Sealed Class: Declared with Sealed keyword, which enables this class to seal all its variables,
methods and properties. No other class can inherit anything from this class or in other words, this class
cannot be inherited. But we can instantiate this class, i.e we can have any number of objects of a
sealed class.
Abstract Class: Declared with abstract keyword, this class is primarily created as a
Inheritable class. An abstract class enables other classes to inherit from this class, but forbids to
instantiate. One can inherit from an abstract class but we cannot create objects of an abstract class.
Abstract class can have abstract as well as non abstract methods. Abstract methods are those which
are not having method definition.

What is OOPS?
Object-Oriented Programming System (OOPs) is a programming concept that works on the
principles of abstraction, encapsulation, inheritance, and polymorphism. It allows users to
create objects they want and create methods to handle those objects. The basic concept of
OOPs is to create objects, re-use them throughout the program, and manipulate these
objects to get results.

1) Class
The class is one of the Basic concepts of OOPs which is a group of similar entities. It
is only a logical component and not the physical entity.
2) Object
An object can be defined as an instance of a class, and there can be multiple
instances of a class in a program.

3) Inheritance
Inheritance is one of the Basic Concepts of OOPs in which one object acquires the
properties and behaviors of the parent object. It’s creating a parent-child
relationship between two classes. It offers robust and natural mechanism for
organizing and structure of any software.

4) Polymorphism
Polymorphism is the ability of a variable, object or function to take on multiple
forms. For example, in English, the verb run has a different meaning if you use it
with a laptop, a foot race, and business. Here, we understand the meaning
of run based on the other words used along with it. The same also applied to
Polymorphism.

5) Abstraction
Abstraction : Abstraction is the process of showing only essential/necessary
features of an entity/object to the outside world and hide the other irrelevant
information. For example to open your TV we only have a power button, It is not
required to understand how infra-red waves are getting generated in TV remote
control.
Advantages of Abstraction
• • It reduces the complexity of viewing the things.
• • Avoids code duplication and increases reusability.
• • Helps to increase security of an application or program as only important
details are provided to the user.
6) Encapsulation
Encapsulation is one of the best Java OOPs concepts of wrapping the data and
code. In this OOPs concept, the variables of a class are always hidden from other
classes. It can only be accessed using the methods of their current class. For
example – in school, a student cannot exist without a class.

Difference between abstraction and encapsulation:


Encapsulation is data hiding(information hiding) while Abstraction is
detail hiding(implementation hiding).
While encapsulation groups together data and methods that act upon the
data, data abstraction deals with exposing to the user and hiding the
details of implementation.

Difference between Ref and Out keywords in C#

The out is a keyword in C# which is used for the passing the


arguments to methods as a reference type. It is generally used when a
method returns multiple values. The out parameter does not pass the
property.
// C# program to illustrate the

// concept of out parameter

using System;

class GFG {

// Main method

static public void Main()

// Declaring variable

// without assigning value

int G;

// Pass variable G to the method

// using out keyword

Sum(out G);

// Display the value G

Console.WriteLine("The sum of" +

" the value is: {0}", G);

}
// Method in which out parameter is passed

// and this method returns the value of

// the passed parameter

public static void Sum(out int G)

G = 80;

G += G;

}
}

The ref is a keyword in C# which is used for the passing the arguments by a
reference. Or we can say that if any changes made in this argument in the
method will reflect in that variable when the control return to the calling method.
The ref parameter does not pass the property.
class GFG {

// Main Method
public static void Main()
{

// Assign string value


string str = "Geek";

// Pass as a reference parameter


SetValue(ref str);

// Display the given string


Console.WriteLine(str);
}

static void SetValue(ref string str1)


{

// Check parameter value


if (str1 == "Geek") {
Console.WriteLine("Hello!!Geek");
}

// Assign the new value


// of the parameter
str1 = "GeeksforGeeks";
}
}

Overloading

Overloading is the ability to have multiple methods within the


same class with the same name, but with different parameters.
Each of these methods has their own implementation as well,
meaning that they can behave differently depending on what is
passed in.

Overloading is known as compile-time (or static) polymorphism


because each of the different overloaded methods is resolved
when the application is compiled.
var calc = new Calculator();

int a = 5;

int b = 6;

// calls int Add(int a, int b)

calc.Add(a, b);

double c = 4.2

double d = 5.41

double e = 2.57

// calls double Add(double a, double b, double c)

calc.Add(c, d, e);

Overriding

Overriding, on the other hand, is the ability to redefine the


implementation of a method in a class that inherits from a
parent class. When a method is overridden, the name and the
parameters stay the same, but the implementation that gets
called depends on the type of the object that's calling it.

Overriding is known as runtime (or dynamic) polymorphism


because the type of the calling object is not known until runtime,
and therefore the method implementation that runs is
determined at runtime.
class parentClass{

public virtual void Disp(int i)

System.Console.WriteLine("parentClass Display" + i);

class childClass : parentClass

public override void Disp(int i)

System.Console.WriteLine("childClass Display" + i);

What is the Difference Between Overriding


and Overloading in C#?
Overriding vs Overloading in C#
Overriding in C# is to provide a specific
Overloading in C# is to create multiple
implementation in a derived class method
methods with the same name with
for a method already existing in the base
different implementations.
class.

Parameters

In C# Overloading, the methods have


In C# Overriding, the methods have the
the same name but a different number
same name, same parameter types and a
of parameters or a different type of
same number of parameters.
parameters.

Occurrence

In C#, overriding occurs within the base In C#, overloading occurs within the
class and the derived class. same class.

Binding Time

The binding of the overloaded method


The binding of the overridden method call
call to its definition happens at compile
to its definition happens at runtime.
time.

Synonyms

Overriding is called as runtime Overloading is called as compile time


polymorphism, dynamic polymorphism, static
polymorphism or late binding. polymorphism or early binding.

What is an Abstract Class in C#?


A class that is declared by using the keyword abstract is called an abstract class. An
abstract class is a partially implemented class used for developing some of the operations
which are common for all next level subclasses. So it contains both abstract methods,
concrete methods including variables, properties, and indexers.

When to use Abstract class Instead of


Interface in C#?
The Abstract classes offer default functionality for the derived classes.
It is a great choice if you want to share a common code among several
closely related classes. It acts as a base class and provides the
common code implementation to the derived classes.

An abstract class can be used to achieve versioning of the components


because by adding the new functionality to the base class all the
derived classes will get updated automatically. An interface on the
other hand can’t be modified once created and inherited by the
classes. If we want to add a new method to the interface, we must
create a new interface.

You can go with the abstract class if you wanted to provide the default
implementation to all the subclasses.

The Abstract class allows code reusability.

You can use an abstract class if we don’t want to implement all of the
methods in a derived class but only some of them in a parent class.

What are the advantages of using interfaces?

1. Interfaces allow us to implement polymorphic behavior. Of course, abstract classes


can also be used to implement polymorphic behavior.
2. The Interfaces allow us to develop very loosely coupled systems.
3. Interfaces enable mocking for better unit testing.
4. The Interfaces enable us to implement multiple inheritances in C#.
5. Interfaces are great for implementing Inversion of Control or Dependency Injection.
6. The Interfaces enable parallel application development.

Abstract class vs interface


1. An abstract class doesn't provide full abstraction but an interface does
provide full abstraction; i.e. both a declaration and a definition is given in an
abstract class but not so in an interface.
2. Using abstract we cannot achieve multiple inheritance but using an Interface
we can achieve multiple inheritance.
3. We can not declare a member field in an Interface.
4. We can not use any access modifier i.e. public, private, protected, internal
etc. because within an interface by default everything is public.
5. An Interface member cannot be defined using the keyword static, virtual,
abstract or sealed.

When to use an Interface in C#?


You can achieve loose coupling by using the interface.

An interface can be used when you want the derived classes to fully
implement all of the methods introduced in the base class.

Abstraction can be achieved via interfaces.

Interface Allows you to decouple a method’s definition from its


inheritance hierarchy.

An interface can be used to achieve polymorphic behavior, a single


method of an Interface can have multiple redefinitions into multiple
classes of unrelated types. Here, every derived class is free to provide
its own implementation.

Multiple inheritance is possible using interfaces in C#. however, a class


cannot be inherited from multiple abstract classes.

Constructor
Special method of the class that is automatically invoked when an instance of the class is created is called
a constructor.
The main use of constructors is to initialize the private fields of the class while creating an instance for
the class.
• • The constructor in C# has the same name as class or struct.
• • A class can have any number of constructors.
• • A constructor doesn't have any return type, not even void.
• • A static constructor can not be a parametrized constructor.
• • Within a class, you can create one static constructor only.

Type of constructor
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

Default Constructor:
A constructor without any parameters is called a default constructor; in other words, this type of
constructor does not take parameters.
The drawback of a default constructor is that every instance of the class will be initialized to the same
values and it is not possible to initialize each instance of the class with different values.
Parameterized Constructor:
A constructor with at least one parameter is called a parameterized constructor. The advantage of a
parameterized constructor is that you can initialize each instance of the class with a different value.
Copy Constructor:
The constructor which creates an object by copying variables from another object is called a copy
constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing
instance.
Static Constructor:
When a constructor is created using a static keyword, it will be invoked only once for all of the instances
of the class and it is invoked during the creation of the first instance of the class or the first reference to a
static member in the class. A static constructor is used to initialize static fields of the class and to write the
code that needs to be executed only once.
A static constructor does not take access modifiers or have parameters.
Private Constructor:
When a constructor is created with a private specifier, it is not possible for other classes to derive from
this class, neither is it possible to create an instance of this class.
They are usually used in classes that contain static members only.

Points To Remember :
 It is the implementation of a singleton class pattern.
 use private constructor when we have only static members.
 Using private constructor, prevents the creation of the instances of
that class.

String and String Builder


String
String is immutable, Immutable means if you create string object then you cannot modify it and It always
create new object of string type in memory.
String Builder
StringBuilder is mutable, means if create string builder object then you can perform any operation like
insert, replace or append without creating new instance for every time.it will update string at one place in
memory doesn’t create new space in memory.

Base keyword
We can use the base keyword to access the fields of the base class within derived class. It is useful if base
and derived classes have the same fields. If derived class doesn't define same field, there is no need to use
base keyword. Base class field can be directly accessed by the derived class.

Yield Keyword
The functionality this keyword provides is that when iterating a list, we can read an element of the loop,
return to the calling code and go back to the loop again at the same point, from where it left the loop and
continue processing the records in the loop. So this will be the basic idea behind the example that we will
be using.

Sealed class
C# sealed keyword applies restrictions on the class and method. If you create a sealed class, it cannot be
derived. If you create a sealed method, it cannot be overridden.

Static class
It is the type of class that cannot be instantiated, in other words we cannot create an object of that class
using the new keyword, such that class members can be called directly using their class name.

Difference between sealed and static class


Sealed classes:
1)Can create instances, but cannot inherit
2)Can contain static as well as non static members.
Static classes:
1)Can neither create their instances, nor inherit them
2)Can have static members only.

Method Hiding
A concept to hide the methods of the base class from derived class, this concept is known as Method
Hiding. It is also known as Method Shadowing.
In method hiding, you can hide the implementation of the methods of a base class from the derived
class using the new keyword. Or in other words, in method hiding, you can redefine the method of the
base class in the derived class by using the new keyword.

What is a partial class in C#?


A partial class is a special feature of C#. It provides a special ability to implement the
functionality of a single class into multiple files and all these files are combined into a
single class file when the application is compiled. A partial class is created by using a
partial keyword.

Difference between var and dynamic in C#


Var Dynamic

It is introduced in C# 3.0. It is introduced in C# 4.0

The variables are declared using


The variables are declared using var dynamic keyword are dynamically
keyword are statically typed. typed.

The type of the variable is decided by the The type of the variable is decided
compiler at compile time. by the compiler at run time.

The variable of this type need not


The variable of this type should be be initialized at the time of
initialized at the time of declaration. So that declaration. Because the compiler
the compiler will decide the type of the does not know the type of the
variable according to the value it initialized. variable at compile time.

If the variable does not initialized it throw If the variable does not initialized it
an error. will not throw an error.

It does not support intelliSense in


It support intelliSense in visual studio. visual studio

dynamic myvalue = 10; //


statement 1
var myvalue = 10; // statement 1 myvalue = “GeeksforGeeks”; //
myvalue = “GeeksforGeeks”; // statement 2 statement 2
Here the compiler will throw an error Here, the compiler will not throw an
because the compiler has already decided error though the type of the
the type of the myvalue variable using myvalue is an integer. When you
statement 1 that is an integer type. When assign a string to myvalue it
you try to assign a string to myvalue recreates the type of the myvalue
variable, then the compiler will give an and accepts string without any
error because it violating safety rule type. error.

It cannot be used for properties or returning


values from the function. It can only used It can be used for properties or
as a local variable in function. returning values from the function
Collections

C# collection types are designed to store, manage and manipulate similar data more efficiently.
Data manipulation includes adding, removing, finding, and inserting data in the collection.
Collection types implement the following common functionality:
• • Adding and inserting items to a collection
• • Removing items from a collection
• • Finding, sorting, searching items
• • Replacing items
• • Copy and clone collections and items
• • Capacity and Count properties to find the capacity of the collection and number of items
in the collection

.NET supports two types of collections, generic collections and non-generic collections.
In non-generic collections, each element can represent a value of a different type. The collection
size is not fixed. Items from the collection can be added or removed at runtime.
Types of non-generic collections:
1. ArrayList
2. HashTable
3. SortedList
4. Stack
5. Queue

Generic Collections
A generic collection is strongly typed (you can store one type of objects into it) so that we can
eliminate runtime type mismatches, it improves the performance by avoiding boxing and
unboxing.
It can accept all types of the object at runtime.
Types:
• • List
• • Dictionary
• • Generics
• • Queues Generics

Difference between Array and ArrayList


1.Array stores a fixed number of elements. The size of an Array must be specified at the time of
initialization.
ArrayList grows automatically and you don't need to specify the size.
2.Array is strongly typed. This means that an array can store only specific type of items\
elements.
ArrayList can store any type of items\elements.
3. No need to cast elements of an array while retrieving because it is strongly typed and stores a
specific type of items only.
The items of ArrayList need to be cast to an appropriate data type while retrieving. So, boxing
and unboxing happens.
4. Array performs faster than ArrayList because it is strongly typed.
Performs slows because of boxing and unboxing.
Delegate
Delegate is a basically function pointer that passes a method as a parameter of other methods.
For this purpose we create and use delegates.
• • A delegate is a class that encapsulates a method signature.
• • Delegates are mainly used in implementing the call-back methods and events.
• • Delegates can be chained together as two or more methods can be called on a single
event.

Tuples
Tuple is a data structure that is used to store sequence of elements. Tuple with n elements are
known as n-tuple.
We can use Tuple for the following reasons.
• • To represent a single set of data
• • To provide easy access and manipulation of data
• • To return multiple values from a method without using out parameter
• • To pass multiple values to a method through a single parameter

Early binding and Late binding


Early binding:
It recognizes and checks the methods, or properties during compile time. In this binding, the
compiler already knows about what kind of object it is and what are the methods or properties it
holds.
The performance of early binding is fast and it is easy to code. It decreases the number of run-
time errors.
Late binding:
In late binding, the compiler does not know about what kind of object it is and what are the
methods or properties it holds, here the objects are dynamic objects.
The performance of late binding is slower than early binding because it requires lookups at run-
time.

Dependency Injection
Dependency Injection (DI) is a software design pattern. It allows us to develop loosely-coupled code.
The intent of Dependency Injection is to make code maintainable. Dependency Injection helps to reduce
the tight coupling among software components.
Dependency Injection reduces the hard-coded dependencies among your classes by injecting those
dependencies at run time instead of design time technically.
Design Pattern
Design Patterns are nothing but documented and tested solutions for recurring problems in a given
context. So, in simple words, we can say that the Design Patterns are reusable solutions to the problems
that as a developer we encounter in our day to day programming.
Types of design pattern
• • Creational Design Pattern
• • Structural Design Pattern
• • Behavioral Design Pattern

Repository Pattern
A Repository in C# mediates between the domain and data mapping layers.
Repository pattern C# is a way to implement data access by encapsulating the set of objects persisted in
a data store and the operations performed over them, providing a more object-oriented view of the
persistence layer.
In other words, we can say that a Repository Design Pattern acts as a middleman or middle layer
between the rest of the application and the data access logic.
Loose and Tight Coupling
Loose Coupling means reducing dependencies of a class that use a different class directly.
In tight coupling, classes and objects are dependent on one another.
In general, tight coupling is usually bad because it reduces flexibility and re-usability of code and it
makes changes much more difficult and impedes testability etc.
SOLID principles
SOLID principles are the design principles that enable us to manage most of the software design
problems. These principles provide us with ways to move from tightly coupled code and little
encapsulation to the desired results of loosely coupled and encapsulated real needs of a business
properly.
1. S: Single Responsibility Principle (SRP)
2. O: Open closed Principle (OCP)
3. L: Liskov substitution Principle (LSP)
4. I: Interface Segregation Principle (ISP)
5. D: Dependency Inversion Principle (DIP)

Single Responsibility Principle (SRP):


This means that every class, or similar structure, in your code should have only one
job to do.
Open/Closed Principle
The Open/closed Principle says "A software module/class is open for extension
and closed for modification".
Liskov Substitution Principle
you should be able to use any derived class instead of a parent class and have it
behave in the same manner without modification.
Interface Segregation Principle (ISP)
User should not be forced to implement interfaces they don't use. Instead of one fat
interface, many small interfaces are preferred based on groups of methods, each
one serving one submodule.
Dependency Inversion Principle
High-level modules/classes should not depend on low-level modules/classes. Both
should depend upon abstractions. Secondly, abstractions should not depend upon
details. Details should depend upon abstractions.
Access Modifiers
Public: If you define an attribute or method as public, it can be accessed
from any code of the project.
Private: A private defined attribute or method can be accessed by any
code within the containing class only.
Protected: If you define the method or attribute as protected it can be
accessed by any method in the inherited classes and any method within
the same class.
Internal: If you define an attribute or a method as internal, it is
restricted to classes within the current position assembly.
Protected internal: If you define an attribute or method as protected
internal, access is restricted to classes within the current project
assembly or types derived from the containing class.
Garbage Collection
Automatic memory management is made possible by Garbage
Collection in .NET Framework. When a class object is created at
runtime, certain memory space is allocated to it in the heap memory.
However, after all the actions related to the object are completed in the
program, the memory space allocated to it is a waste as it cannot be
used. In this case, garbage collection is very useful as it automatically
releases the memory space after it is no longer required.
Garbage collection will always work on Managed Heap and internally it
has an Engine which is known as the Optimization Engine.
Garbage Collection occurs if at least one of multiple conditions is
satisfied.
These conditions are given as follows:
• • If the system has low physical memory, then garbage collection
is necessary.
• • If the memory allocated to various objects in the heap memory
exceeds a pre-set threshold, then garbage collection occurs.
• • If the GC.Collect method is called, then garbage collection
occurs. However, this method is only called under unusual situations as
normally garbage collector runs automatically.

Model Binding
Model binder allows you to map Http Request data with the model.
Model binding is a well-designed bridge between the HTTP request and
the C# action methods. It makes it easy for developers to work with
data on forms (views), because POST and GET is automatically
transferred into a data model you specify. ASP.NET MVC uses default
binders to complete this behind the scene.
[HttpPost]
public ActionResult Create(FormCollection collection){
try{
// TODO: Add insert logic here
return RedirectToAction("Index");
}catch{
return View();
}
}
Extension Method
The extension method concept allows you to add new methods in the existing
class or in the structure without modifying the source code of the original type
and you do not require any kind of special permission from the original type and
there is no need to re-compile the original type.
Difference Between Const, ReadOnly and Static ReadOnly
Const is nothing but "constant", a variable of which the value is constant but at
compile time. And it's mandatory to assign a value to it. By default a const is static
and we cannot change the value of a const variable throughout the entire
program.
Readonly is the keyword whose value we can change during runtime or we can
assign it at run time but only through the non-static constructor.
A Static Readonly type variable's value can be assigned at runtime or assigned at
compile time and changed at runtime. But this variable's value can only be
changed in the static constructor. And cannot be changed further. It can change
only once at runtime
Key Difference – Field vs Property in C#
The key difference between field and property in C# is that a field is a variable of
any type that is declared directly in the class.
While property is a member that provides a flexible mechanism to read, write or
compute the value of a private field.

What is the difference between Finalize and Dispose


Dispose There are some resources like windows handles, database connections,
network connections, files, etc. which cannot be collected by the Garbage
Collector. If we want to explicitly release some specific objects then this is the
best to implement IDisposable and override the Dispose() method of IDisposable
interface.
The Dispose() method is not called automatically and we must explicitly call it
from a client application when an object is no longer needed. Dispose() can be
called even if other references to the object are alive.
Finalize
Finalize() is called by the Garbage Collector before an object that is eligible for
collection is reclaimed. Garbage collector will take the responsibility to deallocate
the memory for the unreferenced object. The Garbage Collector calls this method
at some point after there are no longer valid references to that object in memory.
The framework does not guarantee that when this will happen, we can force for
Garbage Collection but it will hurt performance of a program. Finalize() belongs to
the Object class and it will be called by the runtime.

Eager and lazy loading


Q.2. Eager loading and lazy loading?
In LINQ and Entity Framework, you have Lazy Loading and Eager Loading for
loading the related entities of an entity.
Lazy/Deferred Loading:
In case of lazy loading, related objects (child objects) are not loaded automatically
with its parent object until they are requested. By default LINQ supports lazy
loading.
For example, when we run the query given below, UserDetails table will not be
loaded along with the User table.
User usr = dbContext.Users.FirstOrDefault(a => a.UserId == userId);
Eager loading:
1.In case of eager loading, related objects (child objects) are loaded automatically
with its parent object. To use Eager loading you need to use Include() method.
2.Eager Loading helps you to load all your needed entities at once; i.e., all your
child entities will be loaded at single database call. This can be achieved, using the
Include method, which return No index entries found. The related entities as a
part of the query and a large amount of data is loaded at once.
For example, you have a User table and a UserDetails table (related entity to User
table), then you will write the For example, you have a User table and a
UserDetails table (related entity to User table), then you will write the code given
below. Here, we are loading the user with the Id equal to userId along with the user
details.
User usr = dbContext.Users.Include(a => a.UserDetails).FirstOrDefault(a =>
a.UserId == userId);
Difference between IEnumerable and IQueryable
While query data from a database, IEnumerable execute a select query on the
server side, load data in-memory on a client-side and then filter data.
While query data from a database, IQueryable execute the select query on the
server side with all filters.

You might also like