Oops c# Interview
Oops c# Interview
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.
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.
Ref Keyword
The ref keyword passes arguments by reference. It means any changes made to this argument in the
method will be reflected in that variable when control returns to the calling method.
Differences
The ref keyword is used to pass an argument as a reference. This means that when value of that
parameter is changed in the method, it gets reflected in the calling method. An argument that is passed
using a ref keyword must be initialized in the calling method before it is passed to the called method.
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed
without assigning any value to it. An argument that is passed using an out keyword must be initialized in
the called method before it returns back to calling method.
Purpose ref keyword is used when a called out keyword is used when a
1 method has to update the passed called method has to update
parameter. multiple parameter passed.
Direction ref keyword is used to pass data in bi- out keyword is used to get data in
2
directional way. uni-directional way.
OOPS
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
Encapsulation
Encapsulation : Encapsulation means wrapping up data and member function (Method) together into a
single unit i.e. class. Encapsulation automatically achieve the concept of data hiding providing security to
data by making the variable as private and expose the property to access the private data which would
be public.
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.
Inheritance
Inheritance is used to inherit the properties from one class (base) to another (child) class.
The inheritance will enable us to create a new class by inheriting the properties from other classes to
reuse, extend, and modify other class members' behavior based on our requirements.
It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and
reduce the development time.
The inheritance concept is based on a base class and derived class. Let us see the definition of a base
and derived class.
Base class - is the class from which features are to be inherited into another class.
Derived class - it is the class in which the base class features are inherited.
Types of Inheritance:
Single inheritance : It is the type of inheritance in which there is one base class and one derived
class.
Class A(Base class){}
Hierarchical inheritance : This is the type of inheritance in which there are multiple classes derived from
one base class. This type of inheritance is used when there is a requirement of one class feature that is
needed in multiple classes.
Class B:A{}
Class C:A{}
Class D:A{}
Multilevel inheritance: When one class is derived from another derived class then this type of
inheritance is called multilevel inheritance.
Class B:A{}
Class C:B{}
Multiple inheritance using Interfaces: C# does not support multiple inheritances of classes. To
overcome this problem we can use interfaces.
Polymorphism
Polymorphism is a Greek word, meaning "one name many forms". In other words, one object has many
forms or has one name with multiple functionalities. "Poly" means many and "morph" means forms.
Polymorphism provides the ability to a class to have multiple implementations with the same name.
Types of Polymorphism
Method Overloading:
Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a
function in more than one form. A user can implement function overloading by defining two or more
functions in a class sharing the same name. C# can distinguish the methods with different method
signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number
of the parameters, order of the parameters, and data types of the parameters) within the same class.
Why do we need Method Overloading?
If we need to do the same kind of the operation in different ways i.e. for different inputs. In the example
described below, we are doing the addition operation for different inputs. It is hard to find many
different meaningful names for single action.
Method Overriding:
Overriding is a technique that allows the invoking of functions from another class (base class) in the
derived class. Creating a method in the derived class with the same signature as a method in the base
class is called as method overriding.
When a method in a subclass has the same name, same parameters or signature and same return
type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the
method in the super-class. Method overriding is one of the ways by which C# achieve Run Time
Polymorphism(Dynamic Polymorphism).
Example:
class base_class
class Main_Method
{
static void Main()
d.gfg();
Abstract Class
Abstract class is an incomplete class or special class we can't be instantiated. The purpose of an abstract
class is to provide a blueprint for derived classes and set some rules what the derived classes must
implement when they inherit an abstract class.
This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated
directly. This class must contain at least one abstract method, which is marked by the keyword or
modifier abstract in the class definition. The Abstract classes are typically used to define a base class in
the class hierarchy.
Important Points:
The purpose of an abstract class is to provide basic or default functionality as well as common
functionality that multiple derived classes can share and override.
Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully
abstraction because it cannot have method body.
Welcome to GeeksforGeeks!!!
Difference between Abstract Class and Interface
It can contain different types of access It only contains public access modifier
modifiers like public, private, protected because everything in the interface is
etc. public.
The performance of interface is slow
because it requires time to search
The performance of an abstract class actual method in the corresponding
is fast. class.
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.
Static classes:
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.
Partial Class
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.
This keyword is also useful to split the functionality of methods, interfaces, or structure into multiple
files. When you want to chop the functionality of the class, method, interface, or structure into multiple
files, then you should use partial keyword and all the files are mandatory to be available at compile time
for creating the final file.
Advantages:
• With the help of partial classes, multiple developers can work simultaneously in the same class
in different files.
• With the help of a partial class concept, you can split the UI of the design code and the business
logic code to read and understand the code.
• When you were working with automatically generated code, the code can be added to the class
without having to recreate the source file like in Visual studio.
• You can also maintain your application in an efficient manner by compressing large classes into
small ones.
Var Dynamic
The variables are declared using var keyword are The variables are declared using dynamic keyword
statically typed. are dynamically typed.
The type of the variable is decided by the compiler at The type of the variable is decided by the compiler at
compile time. run time.
The variable of this type should be initialized at the The variable of this type need not be initialized at
time of declaration. So that the compiler will decide the time of declaration. Because the compiler does
not know the type of the variable at compile time.
the type of the variable according to the value it
initialized.
If the variable does not initialized it throw an error. If the variable does not initialized it will not throw an
error.
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.
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.
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.
Constructor Chaining
Calling constructor from another constructor is known as constructor chaining . Constructor Chaining
can be done by the keyword this and base.
Static constructor cannot be chained. And a public constructor can access a private constructor with the
help of constructor chaining.
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:
.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.
Types:
• List
• Dictionary
• Generics
• Queues Generics
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.
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.
Tuples
Tuple is a data structure that is used to store sequence of elements. Tuple with n elements are known as
n-tuple.
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.
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.
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)
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".
you should be able to use any derived class instead of a parent class and have it behave in the same
manner without modification.
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.
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.
• 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]
try{
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.
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
While query data from a database, IQueryable execute the select query on the server side with all filters.
While property is a member that provides a flexible mechanism to read, write or compute the value of a
private field.
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.