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

Oops c# Interview

The document discusses various concepts in C# programming, including Eager and Lazy Loading, Ref and Out keywords, Object-Oriented Programming principles such as Abstraction, Encapsulation, Inheritance, and Polymorphism, as well as advanced topics like Abstract Classes, Interfaces, and Constructors. It explains the differences between these concepts and provides examples to illustrate their usage. Additionally, it covers keywords like Base, Yield, Sealed, Static, and Partial Classes, along with the distinctions between Var and Dynamic types.
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)
11 views19 pages

Oops c# Interview

The document discusses various concepts in C# programming, including Eager and Lazy Loading, Ref and Out keywords, Object-Oriented Programming principles such as Abstraction, Encapsulation, Inheritance, and Polymorphism, as well as advanced topics like Abstract Classes, Interfaces, and Constructors. It explains the differences between these concepts and provides examples to illustrate their usage. Additionally, it covers keywords like Base, Yield, Sealed, Static, and Partial Classes, along with the distinctions between Var and Dynamic types.
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
You are on page 1/ 19

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);

Out and Ref Keywords


Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that
an argument/parameter is passed by reference. By default parameters are passed to a method by value.
By using these keywords (ref and out) we can pass a parameter by reference.

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.

Sr. Key ref keyword out keyword


No.

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.

Initialization Before passing a variable as ref, it is No need to initialize variable if


3 required to be initialized otherwise out keyword is used.
compiler will throw error.

Initialization In called method, it is not required to In called method, it is required to


4 initialize the parameter passed as ref. initialize the parameter passed as
out.

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

• 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.

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.

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.

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){}

Class B:A(derived 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 A(base class){}

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 A(base class){}

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

Static / Compile Time Polymorphism(Method Overloading).

Dynamic / Runtime Polymorphism(Method Overriding).

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.

Different ways of doing overloading methods-

Method overloading can be done by changing:

• The number of parameters in two methods.


• The data types of the parameters of methods.
• The Order of the parameters of methods.

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

public void gfg();

class derived_class : base_class

public void gfg();

class Main_Method

{
static void Main()

derived_class d = new derived_class();

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:

• An abstract class cannot be instantiated.


• An abstract class contain abstract members as well as non-abstract members.
• An abstract class cannot be a sealed class because the sealed modifier prevents a class from
being inherited and the abstract modifier requires a class to be inherited.
• A non-abstract class which is derived from an abstract class must include actual
implementations of all the abstract members of parent abstract class.
• An abstract class can be inherited from a class and one or more interfaces.
• An Abstract class can has access modifiers like private, protected, internal with class members.
But abstract members cannot have private access modifier.
• An Abstract class can has instance variables (like constants and fields).
• An abstract class can has constructors and destructor.
• An abstract method is implicitly a virtual method.
• Abstract properties behave like abstract methods.
• An abstract class cannot be inherited by structures.
• An abstract class cannot support multiple inheritance.

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.

• Interfaces specify what a class must do and not how.


• Interfaces can’t have private members.
• By default all the members of Interface are public and abstract.
• The interface will always defined with the help of keyword ‘interface‘.
• Interface cannot contain fields because they represent a particular implementation of data.
• Multiple inheritance is possible with the help of Interfaces but not with classes.

Welcome to GeeksforGeeks!!!
Difference between Abstract Class and Interface

Abstract Class Interface

It contains both declaration and


definition part. It contains only a declaration part.

Multiple inheritance is not achieved by Multiple inheritance is achieved by


abstract class. interface.

It contain constructor. It does not contain constructor.

It can contain static members. It does not contain static members.

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.

It is used to implement the core It is used to implement peripheral


identity of class. abilities of class.

A class can only use one abstract


class. A class can use multiple interface.

If many implementations are of the


same kind and use common behavior, If many implementations only share
then it is superior to use abstract methods, then it is superior to use
class. Interface.

Abstract class can contain methods,


fields, constants, etc. Interface can only contain methods .

It can be fully, partially or not


implemented. It should be fully implemented.

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.

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 and Dynamic Keyword

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.

• 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.

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:

• 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

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.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy