C# basic interview questions for experienced - Part 1
-----------------------------------------------------------------------------------------------------------------------------
Q) What is .NET?
.NET is a free, cross-platform, open-source developer platform for building many different types of applications.
With .NET, you can use multiple
languages, editors, and libraries to build for web, mobile, desktop, games, and
IoT.
Formally, .NET is “an open-source developer
platform, created by Microsoft, for building many different types of
applications. You can write .NET apps in C#, F#, Visual C++, or Visual Basic.”
Informally, .NET is the tool that lets you build
and run C# programs (we’ll avoid F#, Visual C++, Visual Basic for now).
There are a few versions of . NET. They do the
same job but they are meant for different operating systems:
- .NET Framework is the original version of .NET that only
runs on Windows computers.
- .NET Core is the new, cross-platform version of .NET
that runs on Windows, macOS, and Linux computers. Since it’s more flexible, we’ll be using this one throughout the path.
Whenever we refer to “.NET” from now on, we
really mean .NET Core.
-----------------------------------------------------------------------------------------------------------------------------
Q)What is C#?
C#
(C-Sharp) is a programming language developed by Microsoft that runs on the
.NET Framework.
C# is used
to develop web apps, desktop apps, mobile apps, games and much more.
With
the help of C# programming language, we can develop different types of secured
and robust applications:
- Window
applications
- Web applications
- Distributed
applications
- Web service
applications
- Database
applications etc.
C# is a computer
programming language. C# was developed by Microsoft in 2000 that can be used to
develop all kinds of software targeting various platforms including Windows,
Web, and Mobile using just one programming language.
Today, C# is one
of the most popular programming languages in the world. Millions of software
developers use C# to build all kinds of software.
C# is the primary
language for building Microsoft .NET software applications. Developers can
build almost every kind of software using C# including Windows UI apps, console
apps, backend services, cloud APIs, Web services, controls and libraries, server
less applications, Web applications, native iOS and Android apps, AI and
machine learning software, and blockchain applications.
C# is a strongly
typed object-oriented programming language. C# is open source, simple, modern,
flexible.
C# is
fast and open source
C# is open source under the .NET Foundation,
which is governed and run independently of Microsoft. C# language
specifications, compilers, and related tools are open source projects on
Github. While C# language feature design is lead by Microsoft, the open source
community is very active in the language development and improvements.
C# is
cross platform:
C# is cross
platform programming language. You can build .NET applications that can be
deployed on Windows, Linux, and Mac platforms. C# apps can also be deployed in
cloud and containers.
C# is
safe and efficient:
C# is a type safe language. C# does not allow type conversions that may lead to data loss or other problems. C# allows developers to write safe code. C# also focuses on writing efficient code.
----------------------------------------------------------------------------------------------------------------------------
Q) What is .net framework?
.Net Framework is
a software development platform developed by Microsoft for building and running
Windows applications. The .Net framework consists of developer tools,
programming languages, and libraries to build desktop and web applications. It
is also used to build websites, web services, and games.
.Net framework is a part of .net platform, a
collection of technologies for building apps for LINUX, macOS,Window, IOS, Android
an many more.
Architecture of
.net framework:
- .Net framework Architecture
- .Net Components
- .Net framework design principle
.Net framework Architecture:
The basic architecture of the .Net framework is as
shown below
Language->
Winforms/Asp.net/ADO.net
Library->
Framework class library
CLR-> Common
Language Runtime
.NET Components:
The architecture of .Net framework is
based on the following key components like CLR/GarbageCollector/..
.Net framework design principle:
Interoperibility/Portability(cross-platform)/Security/MemoryManagement/Simplified
deployment.
---------------------------------------------------------------------------------------------------------------------------
Class: A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and base classes. In c#, Classes and Objects are interrelated. The class in c# is nothing but a collection of various data members (fields, properties, etc.) and member functions. The object in c# is an instance of a class to access the defined properties and methods. The object is a runtime entity, it is created at runtime.
Structure:
A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.
Class and struct is both user-defined data types, but have some major differences:
Class
Struct
The class is a reference type in C# and it inherits from the System. Object Type.
The struct is a value type in C# and it inherits from System. Value Type.
All the reference types are allocated on heap memory.
All the value types are allocated on stack memory.
Classes can be inherited from other classes
Struct can’t be inherited from other types.
A class can be an abstract type.
A structure can't be abstract.
We can create a default constructor.
Do not have permission to create any default constructor.
Interoperibility/Portability(cross-platform)/Security/MemoryManagement/Simplified deployment.
Class
Struct
The class is a reference type in C# and it inherits from the System. Object Type.
The struct is a value type in C# and it inherits from System. Value Type.
All the reference types are allocated on heap memory.
All the value types are allocated on stack memory.
Classes can be inherited from other classes
Struct can’t be inherited from other types.
A class can be an abstract type.
A structure can't be abstract.
We can create a default constructor.
Do not have permission to create any default constructor.
Q) Difference between a Value Type and a Reference Type:
Value Type
Reference Type
A Value Type holds the data within its own memory allocation(holds both data and memory in the same location.)
Unlike value types, a reference type doesn't store its value directly. In other words, a reference type contains a pointer to another memory location that holds the data.
Value Type variables are stored in the stack.
Reference Type variables are stored in the heap
Ex: int i = 100;
bool,byte,char,decimal,double,enum,float,int,long.
Ex: string s = "Hello World!!";
String,Arrays,Class,Delegate,obj,dynamic.
Value Type
Reference Type
A Value Type holds the data within its own memory allocation(holds both data and memory in the same location.)
Unlike value types, a reference type doesn't store its value directly. In other words, a reference type contains a pointer to another memory location that holds the data.
Value Type variables are stored in the stack.
Reference Type variables are stored in the heap
Ex: int i = 100;
bool,byte,char,decimal,double,enum,float,int,long.
Ex: string s = "Hello World!!";
String,Arrays,Class,Delegate,obj,dynamic.
Q) Difference between a stack and heap memory:
Stack Memory
Heap Memory
Stack is used for static memory allocation
Heap for dynamic memory allocation, both stored in the computer's RAM.
The stack is an array of memory.
- It is a Last-in, First-out (LIFO) data structure.
- Data can be added to and deleted only from the top of the stack.
- Placing a data item at the top of the stack is called pushing the item onto the stack.
- Deleting an item from the top of the stack is called popping the item from the stack.
The heap is an area of memory where chunks are allocated to store certain kinds of data objects. Unlike the stack, data can be stored and removed from the heap in any order. your program can store items in the heap, it cannot explicitly delete them. Instead, the CLR’s garbage collector (GC) automatically cleans up orphaned heap objects when it determines that your code can no longer access them.
Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is dealt with when the program is compiled.
Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory.
Value Type variables are stored in the stack.
Reference Type variables are stored in the heap
Ex: int i = 100;
bool,byte,char,decimal,double,enum,float,int,long.
Ex: string s = "Hello World!!";
String,Arrays,Class,Delegate,obj,dynamic.
-----------------------------------------------------------------------------------------------------------------------------
Managed Code: The code which is executed by CLR (Common Language Runtime) is called Managed Code.
è Any application which is developed in the .Net framework is going to work under CLR.
è CLR internally uses the Garbage Collector to clear the unused memory and also used the other functionalities like CTS, CAS, etc.
è If we need to execute the Managed code application we just need to install .Net framework as we need CLR to execute this code.
Unmanaged Code:
è The unmanaged code is basically developed using other languages (other than .Net Framework), so it uses its own language runtime to execute the applications. The application runtime will take care of its memory management, security, etc.
è Even if we do not install .Net framework the unmanaged code will work properly as it is not depending on the CLR.
è We can also run unmanaged code using managed code by using commands, but even if we run the unmanaged application using .Net code the CLR is not having the control to run that application, the application uses its own runtime to execute.
MANAGED CODE
UNMANAGED CODE
It is executed by managed runtime environment or managed by the CLR.
It is executed directly by the operating system.
It provides security to the application written in .NET Framework.
It does not provide any security to the application.
Memory buffer overflow does not occur.
Memory buffer overflow may occur.
It provides runtime services like Garbage Collection, exception handling, etc.
It does not provide runtime services like Garbage Collection, exception handling, etc.
The source code is compiled in the intermediate language known as IL or MSIL or CIL.
The source code directly compiles into the native language.
It does not provide low-level access to the programmer.
It provides low-level access to the programmer.
-------------------------------------------------------------------------------------------------------------------
Stack Memory
Heap Memory
Stack is used for static memory allocation
Heap for dynamic memory allocation, both stored in the computer's RAM.
The stack is an array of memory.
- It is a Last-in, First-out (LIFO) data structure.
- Data can be added to and deleted only from the top of the stack.
- Placing a data item at the top of the stack is called pushing the item onto the stack.
- Deleting an item from the top of the stack is called popping the item from the stack.
The heap is an area of memory where chunks are allocated to store certain kinds of data objects. Unlike the stack, data can be stored and removed from the heap in any order. your program can store items in the heap, it cannot explicitly delete them. Instead, the CLR’s garbage collector (GC) automatically cleans up orphaned heap objects when it determines that your code can no longer access them.
Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is dealt with when the program is compiled.
Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory.
Value Type variables are stored in the stack.
Reference Type variables are stored in the heap
Ex: int i = 100;
bool,byte,char,decimal,double,enum,float,int,long.
Ex: string s = "Hello World!!";
String,Arrays,Class,Delegate,obj,dynamic.
MANAGED CODE
UNMANAGED CODE
It is executed by managed runtime environment or managed by the CLR.
It is executed directly by the operating system.
It provides security to the application written in .NET Framework.
It does not provide any security to the application.
Memory buffer overflow does not occur.
Memory buffer overflow may occur.
It provides runtime services like Garbage Collection, exception handling, etc.
It does not provide runtime services like Garbage Collection, exception handling, etc.
The source code is compiled in the intermediate language known as IL or MSIL or CIL.
The source code directly compiles into the native language.
It does not provide low-level access to the programmer.
It provides low-level access to the programmer.
What is the use of using statement in C#?
using statement provides some unique features.
- using Directive
Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces, and abstract classes and their methods and properties on the current page. Adding a namespace can be done in the following two ways:
- Using Statement
This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.
3. The main goal is to manage resources and release all the resources automatically which implements the IDisposable interface. You should always use using statement whenever you have to release resources immediately.
- Manage Scope: It also manages the scope of the object. At the end of using block, using calls the Dispose method and in the method, object release all its resources and should not be available further.
- C# provides a special "using" statement to call Dispose method explicitly.
- The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically
- Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection. In other words, if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs, then here the using statement closes the connection automatically. here's no need to call the connection Close() method explicitly.
someClass sClass = new someClass();
try
{
sClass.someAction();
}
finally
{
if (sClass != null)
mine.Dispose();
}
is same as
using (someClass sClass = new someClass())
{
sClass.someAction();
}
In the above code blocks, the second code block is uses the "using" statement, so in this case the objects are disposed as soon as control leaves the block. It provides a convenient syntax that ensures the correct use of IDisposable objects, also we can see implementing using is a of way shorter and easier to read.
Below is syntax for using statement:
1
2
3
4
5
using(SqlHelper sqlHelper = new SqlHelper())
{
// use sqlHelper object
} //automatically calls Dispose method
sqlHelper object is not available outside the using statement.
SqlHelper sqlHelper = new SqlHelper();
try
{
// use sqlHelper object
}
finally
{
if (sqlHelper != null)
{
((IDisposable)sqlHelper).Dispose();
}
}
static void Main(string[] args)
{
string connString = "...";
using(SqlConnection sqlConnection = new SqlConnection(connString))
{
using(SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = "SELECT * FROM Customer";
sqlConnection.Open();
using(SqlDataReader dataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
while(dataReader.Read())
{
//fill your object
}
}
}
}
}
Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces, and abstract classes and their methods and properties on the current page. Adding a namespace can be done in the following two ways:
This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.
1
2
3
4
5
using(SqlHelper sqlHelper = new SqlHelper())
{
// use sqlHelper object
} //automatically calls Dispose method
-----------------------------------------------------------------------------------------------------------------------------
Q) Microsoft Intermediate
language (MSIL) :
Why Partial Compiled Code or why not fully compiled Code?
As a developer, you may be thinking about why the respective language compiler generates partially compiled code or why not fully compiled code i.e. machine code or binary code in .NET Framework. The reason is very simple. We don’t know in what kind of environment .NET Code is going to be run (for example, Windows XP, Windows 7, Windows 10, Windows Server, etc.). In other words, we don’t know what operating system is going to run our application; we also don’t know the CPU configuration, Machine Configuration, Security Configuration, etc. So, the Microsoft Intermediate language (MSIL) or Intermediate language (IL) code is partially compiled, and at runtime, this Microsoft Intermediate language (MSIL) or Intermediate language (IL) code is compiled to machine-specific instructions or you can say binary code using environmental properties such as Operating System, CPU, Machine Configuration, etc. by the CLR in .NET Framework.
JIT (Just-in-Time) Compiler:
The CLR takes the IL (Intermediate Language) code and gives it to something called JIT (Just-in-Time) Compiler. The JIT compiler reads each and every line of the IL code and converts it to machine-specific instructions (i.e. into binary format) which can be executed by the underlying Operating System. The native code (Machine Code or Binary code) is directly understandable by the system hardware. JIT compiles the code just before the execution and then saves this translation in memory.
Common Language Runtime (CLR) :
.NET CLR is a run-time environment that manages and executes the code written in any .NET
programming language. The CLR stands for Common Language Runtime and it is an Execution Environment. It works as a layer
between Operating Systems and the applications written in . NET languages
It converts code
into native code which further can be executed by the CPU.
Common Language Runtime (CLR) in .NET Framework:
- Security
Manager
- JIT Compiler
- Memory
Manager
- Garbage Collector
- Exception Manager
- Common Language Specification(CLS)
- Common Type System(CTS)
- Security
Manager
Security Manager:
- CAS (Code Access Security)
- CV (Code Verification)
These two
components are basically used to check the privileges of the current user that
the user is allowed to access the assembly or not. The Security Manager
also checks what kind of rights or authorities this code has and whether it is
safe to be executed by the Operating System. So, basically, these types of
checks are maintained by the Security Manager in .NET Application.
Memory Manager:
The memory
manager component of CLR in the .NET Framework allocates the necessary memory
for the variables and objects that are to be used by the application.
Garbage Collector:
When a dot net
application runs, lots of objects are created. At a given point in time, it is
possible that some of those objects are not used by the application. So, Garbage Collector in .NET Framework is nothing but is a Small
Routine or you can say it’s a Background Process Thread that
runs periodically and try to identify what objects are not being used currently
by the application and de-allocates the memory of those objects.
Exception Manager:
The Exception Manager component
of CLR in the .NET Framework redirects the control to execute the catch or
finally blocks whenever an exception has occurred at runtime.
Common Type System (CTS) in .NET Framework:
The .NET
Framework supports many programming languages such as C#, VB.NET, J#, etc.
Every programming language has its own data type. One programming language data
type cannot be understood by other programming languages. But, there can be
situations where we need to communicate between two different programming
languages. For example, we need to write code in the VB.NET language and that
code may be called from C# language. In order to ensure smooth communication
between these languages, the most important thing is that they should have a CTS which ensures that data types defined in two
different languages get compiled to a common data type.
CLR in .NET
Framework will execute all programming language’s data types. This is possible
because CLR having its own data types which are common to all programming
languages. At the time of compilation, all
language-specific data types are converted into CLR’s data type. This data type
system of CLR is common to all .NET Supported Programming languages and this is
known as the Common Type System(CTS)
CLS (Common Language
Specification) in .NET Framework:
CLS is a part of CLR in the .NET Framework.
The .NET Framework supports many programming languages such as C#, VB.NET, J#,
etc. Every programming language has its own syntactical rules for writing the
code which is known as language specification. One programming language
syntactical rules (language specification) cannot be understood by other
programming languages. But, there can be situations where we need to
communicate between two different programming languages. In order to ensure smooth communication between different .NET
Supported Programming Languages, the most important thing is that they should
have Common Language Specifications which ensures that language
specifications defined in two different languages get compiled to a Common
Language Specification.
CLR in .NET
Framework will execute all programming language’s code. This is possible
because CLR having its own language specification (syntactical rules) which are
common to all .NET Supported Programming Languages. At the time of compilation, every language compiler should follow
this language specification of CLR and generate the MSIL code. This language
specification of CLR is common for all programming languages and this is known
as Common Language Specification.
-----------------------------------------------------------------------------------------------------------------------------
Q) Garbage Collector:
When a dot net application runs, lots of objects are
created. At a given point in time, it is possible that some of those objects
are not used by the application. So, Garbage Collector in .NET Framework is
nothing but is a Small Routine or you can say it’s a Background Process Thread
that runs periodically and try to identify what objects are not being used
currently by the application and de-allocates the memory of those objects.
Basically, heap is managed by different
'Generations', it stores and handles long-lived and short-lived objects, see
the below generations of Heap:
1. 0
Generation (Zero): This generation holds short-lived objects, e.g., Temporary
objects. GC initiates garbage collection process frequently in this generation.
2. 1
Generation (One): This generation is the buffer between short-lived and
long-lived objects.
3. 2 Generation (Two): This generation holds long-lived objects like a static and global variable, that needs to be persisted for a certain amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similar objects which are not collected in generation One, are then moved to generation 2 and from there onwards, objects remain in the same generation. The objects in generation 2 are long-lived such as static objects as they remain in the heap memory for the whole process duration.
-----------------------------------------------------------------------------------------------------------------------------
Q) What
is assembly?
When
you compile your source code, the generated is .exe or .dll. An Assembly in
.NET is a DLL or EXE file. It's the smallest unit of deployment for any .NET
project.
The
assembly typically contains .NET code in MSIL (Microsoft Intermediate language)
that will be compiled to native code ("JITted" - compiled by the
Just-In-Time compiler) the first time it is executed on a given machine. That
compiled code will also be stored in the assembly and reused on subsequent
calls.
.Net
Assembly Contents
a) Assembly
Manifest - The Metadata that describes the assembly and its contents
b)
Type Metadata - Defines all types, their properties and methods.
c)
MSIL - Microsoft intermediate language
d) A
set of Resources - All other resources like icons, images etc.
Assemblies are basically the following two types:
- Private Assembly
- Shared Assembly
1) Private Assembly:
It is an assembly that is
being used by a single application only.
2)Shared Assembly:
Assemblies
that can be used in more than one project are known to be a shared assembly.
Shared assemblies are generally installed in the GAC. Assemblies that are
installed in the GAC are made available to all the .Net applications on that
machine.
In
order to share an assembly, the assembly must be explicitly built for this
purpose by giving it a cryptographically strong name . By contrast, a private
assembly name need only be unique within the application that uses it.
Strong
name includes the name of the .net assembly, version number, culture identity,
and a public key token. It is generated from an assembly file using the
corresponding private key. Strong names guarantee name uniqueness by relying on
unique key pairs.
To
create a key pair
At
the command prompt, type the following command:
sn
-k fileName
In this command, file name is the name of the output file containing the key pair
-----------------------------------------------------------------------------------------------------------------------------What is
an assembly manifest?
An
assembly manifest is metadata inside an assembly that describes everything
there is to know about the assembly and its contents. . In the . NET Framework,
an assembly manifest is a text file containing metadata about the code within a
CLI assembly.The manifest contains:
• Strong Name – The assembly’s name,
version, culture, optional processor architecture, and public key (for shared
assemblies)
• File Contents – Name and hash of all
files in the assembly
• Type List – Types defined in the
assembly, including public types that are exported from the assembly
• Resource List – Icons, images, text
strings and other resources contained in the assembly
• Dependencies – Compile-time
dependencies on other assemblies
• Security – Permissions required for
the assembly to run properly
For
installing an assembly into the GAC we first need to generate strong names for
the assembly because only a strong name assembly is installed in the GAC. All
other assemblies are known as weak named assemblies and they cannot be stored
in the GAC.
The
Assembly Manifest can be stored in Portable Executable (PE) file with Microsoft
Intermediate Language (MSIL) code. You can add or change some information in
the Assembly Manifest by using assembly attributes in your code. The Assembly
Manifest can be stored in either a PE file (an .exe or .dll) with Microsoft
Intermediate Language (MSIL) code or in a standalone PE file that contains only
assembly manifest information. Using ILDasm, you can view the manifest
information for any managed DLL.
The
Ildasm is an utility in C# which shows the information of Assembly in human-readable
format by parsing any .. It also shows the namespaces and types and as well as
their interfaces.As Assembly contains any MSIL code Ildasm.exe shows more than
just the Microsoft intermediate language (MSIL) code.
----------------------------------------------------------------------------------------------------------------------------
Q) What is Global Assembly Cache (GAC)
Every computer where
the CLR is installed has a reserved area for machine wide code i.e known as GAC
(global assembly Cache).
The Global Assembly
Cache (GAC) is a folder in Windows directory to store the .NET assemblies that
are specifically designated to be shared by all applications executed on a
system.
It is an area of memory
reserved to store the assemblies of all .NET applications that are running on a
certain machine.
It shares assemblies
among multiple .NET applications.
Following are the
reasons why it is important to install an assembly into the global assembly
cache:
1. Shared location.
2. File security.
3. Side-by-side
versioning.
4. Additional search
location.
An assembly must have a
strong name to be installed in the GAC.
Unlike in COM, there is
no need for the assembly in GAC to be registered before its use. Each assembly
is accessed globally without any conflict by identifying its name, version,
architecture, culture and public key.
The
GAC is automatically installed with the .NET runtime. The global assembly cache
is located in 'Windows/WinNT' directory and inherits the directory's access
control list that administrators have used to protect the folder.
The Global Assembly Cache Tool (Gacutil.exe), that allows you to view and
manipulate the contents of the Global Assembly Cache.
GAC is
located in %windir%\assembly (for example, C:\WINDOWS\assembly) and it is a
shared repository of libraries.
To view the Contents
of the Global Assembly Cache (GAC)
At the
Visual Studio command prompt, type the following command:
gacutil -l or gacutil /l-----------------------------------------------------------------------------------------------------------------------------
What is a Satellite Assembly?
A satellite assembly is a .NET
Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place resources for
different languages in different assemblies, and the correct assembly is loaded
into memory only if the user selects to view the application in that language.
Use
the Assembly Linker (Al.exe) to compile .resources files into satellite
assemblies. Al.exe creates an assembly from the .resources files that you
specify. By definition, satellite assemblies can only contain resources. They
cannot contain any executable code.
Satellite Assemblies = Compilation of
(Resource file + Main Assemblies)
This means
that you develop your application in a default language and add flexibility to
react with change in the locale. Say, for example, you developed your
application in an en-US locale. Now, your application has multilingual support.
When you deploy your code in, say, India, you want to show labels, messages
shown in the national language which is other than English.
Satellite
assemblies give this flexibility. You create any simple text file with
translated strings, create resources, and put them into the bin\debug folder.
That's it. The next time, your code will read the CurrentCulture property of
the current thread and accordingly load the appropriate resource.
-----------------------------------------------------------------------------------------------------------------------------
Q) Reflection
in c#
Reflection objects
are used for obtaining type information at runtime. The classes that give
access to the metadata of a running program are in the System. Reflection namespace.
The System. Reflection namespace
contains classes that allow you to obtain information about the application and
to dynamically add types, values, and objects to the application.
Applications of Reflection
Reflection has the following applications −
·
It allows view
attribute information at runtime.
·
It allows
examining various types in an assembly and instantiate these types.
·
It allows late
binding to methods and properties
·
It allows
creating new types at runtime and then performs some tasks using those types.
Viewing Metadata:
using reflection you can view the attribute
information.
The MemberInfo object of the System.Reflection class
needs to be initialized for discovering the attributes associated with a class.
To do this, you define an object of the target class, as –
System.Reflection.MemberInfo
info=typeof(MyClass);
-----------------------------------------------------------------------------------------------------------------------------
Difference between
DLL and exe
SNO
DLL
EXE
1
Can not run Individually
Runs Individually
2
Used as supportive file for other Application
Itself an Application
3
Does not contain an entry point (no main
function) so can not run individually
Contains an entry point (Main function) so can
run individually
4
A Program /Application with out main creates a
DLL after compilation.
A Program /Application With main creates an EXE
after compilation.
5
OS does not create a separate process for any
DLL rather DLL will run in the same process created for an EXE
OS Creates a separate process for each EXE it
executes.
----------------------------------------------------------------------------------------------------------------------------
Difference Between Finalize and Dispose Method IN C#?
SNO
DLL
EXE
1
Can not run Individually
Runs Individually
2
Used as supportive file for other Application
Itself an Application
3
Does not contain an entry point (no main
function) so can not run individually
Contains an entry point (Main function) so can
run individually
4
A Program /Application with out main creates a
DLL after compilation.
A Program /Application With main creates an EXE
after compilation.
5
OS does not create a separate process for any
DLL rather DLL will run in the same process created for an EXE
OS Creates a separate process for each EXE it
executes.
Dispose
|
Finalize
|
It is
used to free unmanaged resources like files, database connections etc. at any
time. |
It can be
used to free unmanaged resources (when you implement it) like files, database
connections etc. held by an object before that object is destroyed. |
Explicitly,
it is called by user code and the class which is implementing dispose method,
must has to implement IDisposable interface. |
Internally,
it is called by Garbage Collector and cannot be called by user code. |
It
belongs to IDisposable interface. |
It
belongs to Object class. |
It's
implemented by implementing IDisposable interface Dispose() method. |
It's
implemented with the help of destructor in C++ & C#. |
There is
no performance costs associated with Dispose method. |
There is
performance costs associated with Finalize method since it doesn't clean the
memory immediately and called by GC automatically. |
-----------------------------------------------------------------------------------------------------------------------------
Difference between Namespace and Assembly?
Namespace :
It is a Collection of names wherein each name is
Unique. They form the logical boundary for a Group of classes.
Namespace is the logical naming decided at design
time by the developer.
· Namespace contains a set of unique names. Namespace can include multiple assemblies.
·
It is an output unit
·
It is a unit of Deployment & a unit of
versioning.
·
Assemblies contain MSIL code. [e.g.
metadata,manifest]
·
An assembly is the primary building block of a
.NET Framework application.
·
Scope for a particular type is defined at run time using
Assembly
-----------------------------------------------------------------------------------------------------------------------------
Difference between array and array list in c#?
Array:
An Array is a collection of data items of the same
type. An Array is reference type so memory for the array is allocated on
the heap. We can initialize an Array using the "new" operator
and by specifying the type and number of elements inside the Array.
Array Declaration & Initialization:
int[]
arr = new int[5]
int[]
arr = new int[5]{1, 2, 3, 4, 5};
int[]
arr = {1, 2, 3, 4, 5};
1,2,3,4,5->data
0,1,2,3,4->index
ArrayList:
ArrayList implements the IList interface. ArrayList is one of
the most flexible data structures from C# collection. Collection classes are
special classes for data storage and retrieval.
EXAMPLE
ArrayList Declaration & Initialization:
ArrayList
arList = new ArrayList();
arList.Add(1);
arList.Add("Two");
arList.Add(false);
Array |
ArrayList |
An Array is strongly-typed. We can store only
the same type of data. |
ArrayList is a non-generic collection type.
ArrayList's internal Array is of the object type. So, we can store multiple
types of data in ArrayList. |
Array stores a fixed number of elements. |
ArrayList is dynamic in term of capacity. If
the number of element exceeds, ArrayList will increase to double its current
size. |
Array provides better performance than
ArrayList. |
If we are using a large number of
ArrayList then it degrades performance because of boxing and unboxing. |
Array uses static helper class Array which
belongs to system namespace |
ArrayList implements an IList interface
so, it provides a method that we can use for easy implementation. |
Array belongs to namespace System |
ArrayList belongs to namespace System.Collection |
The Array cannot accept null. |
An Arraylist can accept null. |
Example - |
Example:ArrayList a1=new
ArryList();a1.add(null);a1.insert(1,”hi”);a1.add(3);a1.add(8.23); |
---------------------------------------------------------------------------------------------------------------------What’s the
difference between the Array.CopyTo() and Array.Clone()?
Array.CopyTo copies the elements of one array to another pre-existing array starting from a given index (usually 0). Both arrays must be single-dimensional.
Array. Clone
creates a copy of an array as an object. It, therefore, needs to be cast to the
actual array type before it can be used to do very much. It works on both
single and multi-dimensional arrays.
In both cases, the
copies are shallow copies i.e. in the case of reference types only the
references are copied - the objects to which they refer are not copied.
-----------------------------------------------------------------------------------------------------------------------
Boxing:The
process of converting from a value type to a reference type is called boxing.
Boxing is an implicit conversion. Here is an example of boxing in C#.
- // Boxing
- int anum = 123;
- Object obj = anum;
- Console.WriteLine(anum);
- Console.WriteLine(obj);
Unboxing:The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.
- // Unboxing
- Object obj2 = 123; ;
- int anum2 = (int)obj;
- Console.WriteLine(anum2);
- Console.WriteLine(obj);
-----------------------------------------------------------------------------------------------------------------------------
What are indexers
in c#?
C# indexers are usually known as smart arrays. A C# indexer is a class property that allows you to access a member variable of a class or struct using the features of an array. In C#, indexers are created using this keyword. Indexers in C# are applicable on both classes and structs.
Creating an
Indexer
- <modifier> <return type> this [argument list]
- {
- get
- {
- // your get block code
- }
- set
- {
- // your set block code
- }
- }
Important points to remember on indexers:
- Indexers are always created with this keyword.
- Parameterized properties are called indexers.
- Indexers are implemented through get and set accessors for the [ ] operator.
- ref and out parameter modifiers are not permitted in the indexer.
- Indexer is an instance member so can't be static but
property can be static.
- Indexers are used on group of elements.
- Indexer is identified by its signature whereas a
property is identified it's name.
- Indexers are accessed using indexes whereas properties
are accessed by names.
- Indexers can be overloaded.
-----------------------------------------------------------------------------------------------------------------------------
What is enum in C#?
An enum is a set of named integer constants. An “enum” is
a special "class" that represents a group of constants (unchangeable/read-only
variables).
·
An enumerated type is declared using the enum keyword.
·
Enums are value types and are created on the
stack memory.
·
By default, the first item of an enum has the
value 0. The second has the value 1, and so on.
·
Enum values are fixed. Enum can be displayed as a
string and processed as an integer.
·
The default type is int, and the approved types
are byte, sbyte, short, ushort, uint, long, and ulong.
enum Level
{
Low,
Medium,
High
}
Level myVar = Level.Medium;
Console.WriteLine(myVar);
---------------------------------------------------------------------------------------------------------------------------
Difference between
string and string builder in c#
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.
System. String
namespace
String Builder is used to represent a mutable string of characters. Mutable means the string which can be changed.
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 doesnt create new space in memory.
System.Text.StringBuilder
StringBuilder
sb = new StringBuilder();
sb.Append("Prakash");
sb.Append("Tripathi");
Console.WriteLine(sb.ToString());
When to use
which one:
·
If a string is going to remain constant
throughout the program, then use String class object because a String object is
immutable.
·
If a string can change (example: lots of logic
and operations in the construction of the string) then using a StringBuilder is
the best option.
·
Also if you have an array of things to
concatenate, consider calling "String.Concat" explicitly or
"String.Join" if you need a delimiter.
Converting
String to StringBuilder:
To convert a String class object to StringBuilder class object, just pass the
string object to the StringBuilder class constructor.
String str = "Geeks";
//
conversion from String object
//
to StringBuilder
StringBuilder
sbl = new StringBuilder(str);
sbl.Append("ForGeeks");
Console.WriteLine(sbl);
Converting StringBuilder to String:
This conversions can be performed using ToString() method.
StringBuilder sbdr = new StringBuilder("Builder");
//
conversion from StringBuilder
//
object to String using ToString method
String str1 = sbdr.ToString();
Console.Write("StringBuilder
object to String: ");
Console.WriteLine(str1);
----------------------------------------------------------------------------------------------------------------------------------------
What are Generics in C#?
Generics allow you to
define placeholders for fields, methods, parameters, etc. It replaces the
placeholder with some specific type at compile time.
It was introduced in
c# 2.0 under the namespace system. collections.generic namespace.
Generic means the general form, not specific. In C#, generic
means not specific to a particular data type.
C# allows you to define
generic classes, interfaces, abstract classes, fields, methods, static methods,
properties, events, delegates, and operators using the type parameter and
without the specific data type. A type parameter is a placeholder for a
particular type specified when creating an instance of the generic type.
Advantages of
Generics:
·
It provides code
reusability.
·
It performs faster as it
does not perform boxing and unboxing.
·
It applies a specified
type at compile time.
· It is type-safe.
-----------------------------------------------------------------------------------------------------------------------
What is a Hashtable in C#?
A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key.
Hashtable Characteristics
- Hashtable stores key-value pairs.
- Comes under System.Collection namespace.
- Implements IDictionary interface.
- Keys must be unique and cannot be null.
- Values can be null or duplicate.
- Values can be accessed by passing associated key in the indexer
e.g. myHashtable[key]
- Elements are stored as DictionaryEntry objects.
- A Hashtable is a
collection of key/value pairs that are arranged based on the hash code of
the key.
- A hash function is provided by
each key object in the Hashtable.
- The Hashtable class implements
the IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback,
and ICloneable interfaces.
- In hashtable, you can store elements of the same type and of the different types.
Creating a Hashtable
The following example demonstrates creating a
Hashtable and adding elements.
Example:
Create and Add Elements
Hashtable numberNames = new Hashtable();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(DictionaryEntry de in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);
//creating a Hashtable using collection-initializer syntax
var cities = new Hashtable(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach(DictionaryEntry de in cities)
Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);
Example: Add Dictionary in Hashtable
Dictionary<int, string> dict = new Dictionary<int,
string>();
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
Hashtable ht = new Hashtable(dict);
Example: Update Hashtable
//creating a Hashtable using
collection-initializer syntax
var cities = new Hashtable(){
{"UK",
"London, Manchester, Birmingham"},
{"USA",
"Chicago, New York, Washington"},
{"India",
"Mumbai, New Delhi, Pune"}
};
string citiesOfUK = (string) cities["UK"];
//cast to string
string citiesOfUSA = (string) cities["USA"]; //cast to string
Console.WriteLine(citiesOfUK);
Console.WriteLine(citiesOfUSA);
cities["UK"] = "Liverpool,
Bristol"; // update value of UK key
cities["USA"] = "Los Angeles, Boston"; // update value of USA key
if(!cities.ContainsKey("France")){
cities["France"]
= "Paris";
}
Example: Remove Elements from Hashtable
var cities = new Hashtable(){
{"UK",
"London, Manchester, Birmingham"},
{"USA",
"Chicago, New York, Washington"},
{"India",
"Mumbai, New Delhi, Pune"}
};
cities.Remove("UK"); // removes UK
//cities.Remove("France"); //throws run-time exception: KeyNotFoundException
if(cities.ContainsKey("France")){ //
check key before removing it
cities.Remove("France");
}
cities.Clear(); //removes all elements
----------------------------------------------------------------------------------------------------------------------------
Q) difference between
hashtable and dictionary in c#
Hashtable |
Dictionary |
A Hashtable is a non-generic collection. |
A Dictionary is a generic collection. |
Hashtable is defined under System. Collections
namespace. |
Dictionary is defined under
System.Collections.Generic namespace. |
In Hashtable, you can store key/value pairs of
the same type or of a different type. |
In Dictionary, you can store key/value pairs of the same type. |
In Hashtable, there is no need to specify the
type of the key and value. |
In Dictionary, you must specify the type of key
and value. |
The data retrieval is slower than Dictionary
due to boxing/ unboxing. |
The data retrieval is faster than Hashtable due
to no boxing/ unboxing. |
In Hashtable, if you try to access a key that
doesn’t present in the given Hashtable, then it will give null values. |
In Dictionary, if you try to access a key that
doesn’t present in the given Dictionary, then it will give an error. |
It is thread-safe. |
It is also thread-safe but only for public
static members. |
It doesn’t maintain the order of stored values. |
It always maintain the order of stored values. |
-----------------------------------------------------------------------------------------------------------------
What is the difference between constant and read-only in C#?
Constant |
Read-only |
||
A constant member is defined at compile-time
and cannot be changed at runtime. public class MyConstClass { public
const double PI = 3.14159; } |
A read-only member can be initialized at runtime, in a constructor as well as being able to be initialized as they are declared. public class MyRoClass { public readonly
double PI = 3.14159; } (or) public class MyRoClass { public readonly
double PI; public MyRoClass() { PI = 3.14159; } } |
||
In C#, constant fields are created using the const keyword. 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. |
In C#, read-only fields can be created using readonly keyword. |
||
The value
of constant is evaluated at compile time |
The value
of readonly is evaluated at run time
|
||
The value of the const field can not be changed. |
The value of read-only field can be changed. |
||
In const fields, we can only assign values in the declaration part. |
In
read-only fields, we can assign values in the declaration and in the constructor part. |
||
It cannot be used with static modifiers. |
It can be used with static modifiers.
|
||
|
It cannot be declared inside the method.
|
||
Const
field can not be passed as ref or out parameter |
a read-only
field can be pass as ref or out parameters in the constructor context. |
||
The value
is constant for all objects
|
The value may be different depending upon the constructor used (as it belongs to the object of the
class) |
-----------------------------------------------------------------------------------------------------------------------------
What is the difference between ref and out keywords?
Ref |
Out |
The parameter or argument must be initialized first before
it is passed to ref. |
It is not compulsory to initialize a parameter or argument
before it is passed to an out. |
It is not required to assign or initialize the value of a
parameter (which is passed by ref) before returning to the calling method. |
A called method is required to assign or initialize a value
of a parameter (which is passed to an out) before returning to the calling
method. |
Passing a parameter value by Ref is useful when the called
method is also needed to modify the pass parameter. |
Declaring a parameter to an out method is useful when
multiple values need to be returned from a function or method. |
It is not compulsory to initialize a parameter value before
using it in a calling method. |
A parameter value must be initialized within the calling
method before its use. |
When we use REF, data can be passed bi-directionally. |
When we use OUT data is passed only in a unidirectional way
(from the called method to the caller method). |
Both ref and out are treated differently at run
time and they are treated the same at compile time.
The out and ref keywords are useful when we want
to return a value in the same variables that are passed as an argument.
out keyword is used to pass arguments to method
as a reference type and is primary used when a method has to return multiple
values. ref keyword is also used to pass arguments to method as reference type
and is used when existing variable is to be modified in a method.
public
class Example
{
public static void Main() //calling method
{
int val1 = 0; //must be initialized
int val2; //optional
Example1(ref val1);
Console.WriteLine(val1); // val1=1
Example2(out val2);
Console.WriteLine(val2); // val2=2
}
static void Example1(ref int value) //called
method
{
value = 1;
}
static void Example2(out int value) //called
method
{
value = 2; //must be initialized
}
}
/*
Output
1
2
*/
class
MyClass
{
public void Method(out int a) // compiler
error “cannot define overloaded”
{
// method that differ only on ref and
out"
}
public void Method(ref int a)
{
// method that differ only on ref and
out"
}
}
----------------------------------------------------------------------------------------------------------------------
What is linq in c# with example?
The full form of LINQ
is 'Language Integrated Query,' and introduced in .NET
Framework 3.5 to query the data from different sources of data such as
collections, generics, XML documents, ADO.NET Datasets, SQL, Web Services, etc.
in C# and VB.NET
For example, SQL is a
Structured Query Language used to save and retrieve data from a database. In
the same way, LINQ is a structured query syntax built in C# and VB.NET to
retrieve data from different types of data sources such as collections, ADO.Net
DataSet, XML Docs, web service and MS SQL Server and other databases.
Example: LINQ Query to Array
// Data source
string[] names = {"Bill",
"Steve", "James", "Mohan" };
// LINQ Query
var myLinqQuery = from name in names
where name.Contains('a')
select name;
// Query execution
foreach(var name in myLinqQuery)
Console.Write(name
+ " ");
Advantages of LINQ
·
User does not need to learn new query languages
for a different type of data source or data format.
·
It increase the readability of the code.
·
Query can be reused.
·
It gives type checking of the object at compile
time.
·
It provides IntelliSense for generic collections.
·
It can be used with array or collections.
·
LINQ supports filtering, sorting, ordering,
grouping.
·
It makes easy debugging because it is integrated
with C# language.
·
It provides easy transformation means you can
easily convert one data type into another data type like transforming SQL data
into XML data.
--------------------------------------------------------------------------------------------------------------------------
What are the differences between IEnumerable and IQueryable?
IEnumerable and IQueryable are used for data
manipulation in LINQ from the database and collections.
IEnumerable |
IQueryable |
IEnumerable exists in the System. Collections namespace. |
IQueryable exists in the System.Linq Namespace. |
IEnumerable is suitable for querying data from in-memory
collections like List, Array and so on. |
IQueryable is suitable for querying data from out-memory
(like remote database, service) collections. |
While querying data from the database, IEnumerable executes
"select query" on the server-side, loads data in-memory on the
client-side and then filters the data. |
While querying data from a database, IQueryable executes a
"select query" on server-side with all filters. |
IEnumerable is beneficial for LINQ to Object
and LINQ to XML queries. |
IQueryable is beneficial for LINQ to SQL
queries. |
IEnumerable doesn’t support lazy loading |
IQueryable support lazy loading |
IEnumerable can move forward only over a
collection, it can’t move backward and between the items. |
IQueryable can move forward only over a
collection, it can’t move backward and between the items. |
It
doesn’t support custom queries. |
It
also supports custom queries using CreateQuery and Executes methods. |
---------------------------------------------------------------------------------------------------------------------------
Q) What is the difference between “continue” and “break” statements in C#?
Using break statement, you can 'jump out of a loop' whereas by using a continue statement, you can 'jump over one iteration' and then resume your loop execution.
The break statement is usually used with the switch statement, and it can also use it within the while loop, do-while loop, or the for-loop. The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.
Break Statement | Continue Statement |
The Break statement is used to exit from the loop constructs. | The continue statement is not used to exit from the loop constructs. |
The break statement is usually used with the switch statement, and it can also use it within the while loop, do-while loop, or the for-loop. | The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop. |
When a break statement is encountered then the control is exited from the loop construct immediately. | When the continue statement is encountered then the control automatically passed from the beginning of the loop statement. |
Syntax: | Syntax: |
-----------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
What is file handling in c#.net with example?
Generally, the
file is used to store the data. The term File Handling refers to the various
operations like creating the file, reading from the file, writing to the file,
appending the file, etc. There is two basic operations which is mostly used in
file handling is reading and writing of the file. The file becomes stream when
we open the file for writing and reading. A stream is a sequence of bytes that
is used for communication. Two streams can be formed from the file one is the input
stream which is used to read the file and another is the output stream is used to
write in the file. In C#, the System.IO namespace contains classes that
handle input and output streams and provide information about file and
directory structure.
Method |
Description |
Close() |
Closes the current StreamWriter object and stream associate
with it. |
Flush() |
Clears all the data from the buffer and writes it in the
stream associate with it. |
Write() |
Write data to the stream. It has different overloads for
different data types to write in the stream. |
WriteLine() |
It is the same as Write() but it adds the newline character at
the end of the data. |
Peek() |
Returns the next available character but does
not consume it. |
Seek() |
It is used to read/write at a specific
location from a file |
Q) Partial class in C#?
Partial classes allow us to split a class into 2 or more files. All these parts are then combined into a single class when the application is compiled. The partial keyword can also be used to split a struct or an interface over two or more files. A partial class is created by using a partial keyword.
Rules
for Partial Methods:
Partial
methods must use the partial keyword and must return void.
Partial
methods can have in or ref but not out parameters.
Partial
methods are implicitly private methods, so cannot be virtual.
Partial
methods can be static methods.
Partial
methods can be generic.
Q)Can Multiple Catch Blocks be executed in C#?
No, multiple catch blocks cannot be executed. Once the first catch block is catched, it will not read the next block. Once the proper catch code is executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.
Yes, we can define multiple catch blocks. The only condition we have to keep in mind is, we should define all derived class exceptions catch block first and then base class exception.
-----------------------------------------------------------------------------------------------------------------------------
·
IndexOutOfRangeException
·
FormatException
·
NullReferenceException
·
DivideByZeroException
·
FileNotFoundException
·
SQLException,
·
OverFlowException-----------------------------------------------------------------------------------------------------------------------------
Q) Explain the difference between Error and
Exception in C#?
Exceptions are those which can be handled at the
runtime whereas errors cannot be handled.
All the Errors are Exceptions but the reverse is not
true. In general, Errors are which nobody can control or guess when it happened
on the other hand Exception can be guessed and can be handled.-----------------------------------------------------------------------------------------------------------------------------
Q) What is the difference between System exceptions
and Application exceptions?
System exceptions are derived directly from a base
class System.SystemException. A System-level Exception is normally thrown when
a nonrecoverable error has occurred.
Application exceptions can be user-defined
exceptions thrown by the applications. If you are designing an application that
needs to create its own exceptions class, you are advised to derive custom
exceptions from the System.ApplicationException class. It is typically thrown
when a recoverable error has occurred.-----------------------------------------------------------------------------------------------------------------------------
Q)Can we catch all exceptions using a single catch
block?
Yes, we can catch all exceptions with a single catch
block with parameter “Exception”. We should use this catch block only for
stopping abnormal termination irrespective of the exceptions thrown from its
corresponding try block.
It is always recommended to write catch blocks with
exception parameters even though we are writing multiple catch blocks. It acts
as a backup catch block.-----------------------------------------------------------------------------------------------------------------------------
Q)When should we write multiple catch blocks for a
single try block?
We should write multiple catch blocks for a single
try block because of the following reasons:
·
To print message specific to an
exception or
·
To execute some logic specific to an
exception
----------------------------------------------------------------------------------------------------------------------------
Q)Why we need finally block in the real-time project?
As per coding standard in finally block we should
write resource releasing logic or clean up the code. Resource releasing logic
means un-referencing objects those are created in the try block. For example,
in real-time projects, we create ADO.NET objects in the try block and at the
end of the try block, we must close these objects.
Since the statements written in try and catch block
are not guaranteed to be executed we must place them in the finally block. For
example, if we want to close ADO objects such as Connection object, Command
object, etc. we must call the close() method in both trials as well as in catch
block to guarantee its execution.
Instead of placing the same close() method call
statements in multiple places if we write it in the finally block it is always
executed irrespective of the exception raised or not raised.-----------------------------------------------------------------------------------------------------------------------------
Difference between SortedList and SortedDictionary
in C#.
SortedList is a collection of key/value pairs that are
sorted according to keys. By default, this collection sort the key/value pairs
in ascending order. It is of both generic and non-generic types of collection.
SortedDictionary is a generic collection that is used to store the key/value pairs in the sorted form and the sorting is done on the key.
Although both are used to compare two objects by
value, still they both are used differently.
int x = 10;
int y = 10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True
Equality operator (==) is a reference type which
means that if equality operator is used, it will return true only if both the
references point to the same object.
Equals() method: Equals method is used to compare
the values carried by the objects. int x=10, int y=10. If x==y is compared
then, the values carried by x and y are compared which is equal and therefore
they return true.
Equality operator: Compares by reference
Equals(): Compares by value----------------------------------------------------------------------------------------------------------------------------
Super
ReplyDelete