Top 50 C# Interview Question.
1. What is the difference between Dispose and Finalize in C#?
In C#, both the Dispose and Finalize methods are used to release
resources, but they serve different purposes and behaviors.
The primary difference between dispose() and finalize() is that the dispose()
must be explicitly invoked by the user and the finalize() is called by the
garbage collector when the object is destroyed.
Or
The Dispose method releases unmanaged resources, such as file
handles or database connections, not automatically managed by
the .NET runtime. The Dispose method is called explicitly by client code
to release resources when they are no longer needed.
And the Finalize method is used to perform cleanup operations on an
object just before it is garbage collected.
2. What is the use of a delegate in C#?
A delegate is an object which refers to a method, or you can say it is a
reference type variable that can hold a reference to the methods. Delegates
in C# are similar to the function pointer in C/C++.
Delegates are derived from the System.MulticastDelegate class.
They have a signature and a return type. A function that is added to delegates
must be compatible with this signature.
Delegates can point to either static or instance methods.
Once a delegate object has been created, it may dynamically invoke the
methods it points to at runtime.
Delegates can call methods synchronously and asynchronously.
1.
3. What is IEnumerable<> in C#?
1. IEnumerable is an interface in C# that allows you to iterate
through a collection of elements, one element at a time. It's the
base interface for all non-generic collections that can be
enumerated.
2. IEnumerable defines one method, GetEnumerator(), which
returns an IEnumerator interface. This method allows read-only
access to a collection.
3. You can use IEnumerable with a foreach statement. For
example, you can use a foreach loop to iterate over a list of
fruits and print each element to the console.
4. What are the differences between IEnumerable and
IQueryable?
5. What happens if the inherited interfaces have conflicting method names?
We don't need to define all if we implement multiple interfaces in the same class
with conflict method names. In other words, we can say if we have conflict
methods in the same class, we can’t implement their body independently in the
same class because of the same name and same signature. Therefore, we must
use the interface name before the method name to remove this method
confiscation.
6. What’s the difference between the Array.CopyTo() and Array.Clone()?
The Array.Clone() method creates a shallow copy of an array. A shallow copy of
Array copies only the elements of the Array, whether reference types or value
types, but it does not copy the objects that the references refer to. The
references in the new Array point to the same objects as those in the original
Array.
The CopyTo() static method of the Array class copies a section of an array to
another array. The CopyTo method copies all the elements of an array to
another one-dimension array. For example, the code listed in Listing nine copies
the contents of an integer array to various object types.
7. Difference between Throw Exception and Throw Clause
The basic difference is that the Throw exception overwrites the stack trace. It is
hard to find the original code line number that has thrown the exception.
Throw basically retains the stack information and adds to the stack information in
the exception that it is thrown.
8. What are Indexers in C#?
C# introduces a new concept known as Indexers, which are used for treating an
object as an array. The indexers are usually known as smart arrays in C#.
However, they are not an essential part of object-oriented programming.
Defining an indexer allows you to create classes that act as virtual arrays. Then,
instances of that class can be accessed using the [] array access operator.
Creating an Indexer
< modifier > <
return type > this[argument list] {
get {
// your get block code
}
set {
// your set block code
}
}
9. Difference between the Equality Operator (==) and Equals() Method in C#.
The == Operator and the Equals() method compare two value type data items or
reference type data items. The Equality Operator (==) is the comparison operator, and
the Equals() method compares the contents of a string. The == Operator compares the
reference identity while the Equals() method compares only contents.
10.What is a multicast delegate in C#?
In C#, a multicast delegate is a delegate that manages references to
multiple handler functions. When the delegate is called, all of the
functions that the multicast delegate references will be called.
11. What's the Difference between the Is and As operators in C#
"is" operator
In C# language, we use the "is" operator to check the object type. If two objects
are of the same type, it returns true; else, it returns false.
"as" operator
The "as" operator behaves similarly to the "is" operator. The only difference is it
returns the object if both are compatible with that type. Else it returns a null.
12.What is an Object Pooling?
Object Pooling in .NET allows objects to be kept in the memory pool so they can
be reused without recreating them.
What does it mean?
An object pool is a container of objects that are ready for use. Whenever there is
a request for a new object, the pool manager will take the request, which will be
served by allocating an object from the pool.
How does it work?
We are going to use the Factory pattern for this purpose. We will have a factory
method, which will take care of the creation of objects. Whenever there is a
request for a new object, the factory method will look into the object pool (we use
Queue object). If there is any object available within the allowed limit, it will
return the object (value object). Otherwise, a new object will be created and
given you back.
13.What is a Virtual Method in C#?
In C# virtual method is a strategy that can be reclassified in derived
classes. We can implement the virtual method in the base class and
derived class. It is utilized when a method’s fundamental work is similar
but in some cases derived class needed additional functionalities. A
virtual method is declared in the parent class that can be overridden in
the child class. We make a virtual method in the base class by using the
virtual keyword and that method is overridden in the derived class using
the Override keyword. It is not necessary for every derived class to
inherit a virtual method, but a virtual method must be created in the base
class. Hence the virtual method is also known as Polymorphism.
14. What is the difference between an Array and ArrayList in C#?
15. What is Serialization in C#?
Serialization in C# converts an object into a stream of bytes to store the object in
memory, a database, or a file. Its main purpose is to save the state of an object
from being able to recreate it when needed. The reverse process is called
deserialization.
There are three types of serialization,
1. Binary serialization (Save your object data into binary format).
2. Soap Serialization (Save your object data into binary format; mainly used in
network-related communication).
3. XmlSerialization (Save your object data into an XML file).
16. How do you use the “using” statement in C#?
There are two ways to use the using keyword in C#. One is as a directive, and
the other is as a statement. Let's explain!
1. 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:
2. Using Statement
This is another way to use the using keyword in C#. It plays a vital role in
improving performance in Garbage Collection.
17. What is a Jagged Array in C#?
A jagged array is an array whose elements are arrays. The elements of a jagged array
can be of different dimensions and sizes. A jagged array is sometimes called an "array
of arrays."
18. What is Multithreading with .NET?
Multithreading allows a program to run multiple threads concurrently. The real
usage of a thread is not about a single sequential thread but rather using
multiple threads in a single program. Multiple threads running at the same time
and performing various tasks are referred to as Multithreading. A thread is
considered a lightweight process because it runs within the context of a program
and takes advantage of the resources allocated for that program.
Or
Multi-threading is a process that contains multiple threads within a single
process. Here each thread performs different activities. For example, we
have a class and this call contains two different methods, now using
multithreading each method is executed by a separate thread. So the
major advantage of multithreading is it works simultaneously, which
means multiple tasks execute at the same time. And also maximizing the
utilization of the CPU because multithreading works on time-sharing
concept mean each thread takes its own time for execution and does not
affect the execution of another thread, this time interval is given by the
operating system.
19. What are Anonymous Types in C#?
Anonymous types allow us to create new types without defining them. This is a
way of defining read-only properties in a single object without having to define
each type explicitly. Here, the Type is generated by the compiler and is
accessible only for the current block of code. The type of properties is also
inferred by the compiler.
We can create anonymous types using the “new” keyword and the object
initializer.
20. What is File Handling in C#.Net?
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 are two basic operations
that are 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.
21. What is Reflection in C#?
Reflection is the process of describing the metadata of types, methods,
and fields in a code. The namespace System. Reflection enables you to
obtain data about the loaded assemblies, the elements within them like
classes, methods, and value types
22.What is a Hashtable in C#?
The Hashtable class represents a collection of key/value pairs that are
organized based on the hash code of the key. This class comes under
the System. Collections namespace. The Hashtable class provides
various types of methods that are used to perform different types of
operations on the hashtables. In Hashtable, keys are used to access the
elements present in the collection. For very large Hashtable objects, you
can increase the maximum capacity to 2 billion elements on a 64-bit
system.
23. What are Custom Control and User Control?
Custom Controls are produced as compiled code. These are easy to use and
can be added to the toolbox. Developers can drag and drop these controls onto
their web forms. User Controls are almost the same as ASP include files. They
are also easy to create. User controls, however, can’t be put in the toolbox. They
also can’t be dragged and dropped from it.
24. What are circular references?
When two or more resources are dependent on each, it causes a lock condition,
and the resources become unusable. This is called a circular reference.
25. List down the commonly used types of exceptions in .net
Commonly used types of exceptions in .NET are:
ArgumentException, ArithmeticException, DivideByZeroException,
OverflowExceptio, InvalidCastException, InvalidOperationException ,
NullReferenceException, OutOfMemoryException ,StackOverflowException
26.What are Custom Exceptions?
In some cases, errors have to be handled according to user requirements.
27. Why can’t you specify the accessibility modifier for methods
inside the interface?
In an interface, there are virtual methods which do not come with method
definition. All the methods present are to be overridden in the derived class. This
is the reason they are all public.
28. What is difference between the “throw” and “throw ex”
in .NET?
29. What are C# attributes and its significance?
C# gives developers an option to define declarative tags on a few entities. For
instance, class and method are known as attributes. The information related to
the attribute can be retrieved during runtime by taking the help of Reflection.
30. What is the difference between directcast and ctype?
If an object is required to have the run-time type similar to a different object, then
DirectCast is used to convert it. When the conversion is between the expression
as well as the type, then Ctype is used.
35. What is garbage collection in C#?
Garbage collection is the process of freeing up memory that is captured by
unwanted objects. When you create a class object, automatically some
memory space is allocated to the object in the heap memory. Now, after you
perform all the actions on the object, the memory space occupied by the object
becomes waste. It is necessary to free up memory.
36. What is Singleton design pattern in C#?
Singleton design pattern in C# is a common design pattern. In this
pattern, a class has just one instance in the program that gives global
access to it. Or we can say that a singleton is a class that permits only
one instance of itself to be made and usually gives simple access to that
instance.
There are different approaches to carry out a singleton design in C#.
Coming up next are the regular attributes of a singleton design.
Private and parameterizes single constructor
Sealed class.
Static variable to hold a reference to the single made example
A public and static method of getting the reference to the made
example.
37. What is tuple in C#?
The word Tuple means “a data structure which consists of the multiple
parts”. So tuple is a data structure that gives you the easiest way to
represent a data set that has multiple values that may/may not be related
to each other. It was introduced in .NET Framework 4.0. In tuple, you can
add elements from 1 to 8. If you try to add elements greater than eight,
then the compiler will throw an error. Tuples are generally used when you
want to create a data structure that contains objects with their properties
and you don’t want to create a separate type for that.
38 Difference between SortedList and SortedDictionary in C#.
39. Explain the four steps involved in the C# code compilation?
There exist four steps in the process of code compilation:
a. Compilation of Source code in managed code
b. Clubbing the newly created code into assembly
c. Loading the CLR (Common Language Runtime)
d. Execution of assembly through CLR
40. What is the Race condition in C#?
When 2 threads access the same resource and try to change it at the same
time, we have a race condition.
41. Why are Async and Await used in C#?
Asynchronous programming processes execute independently of the primary
or other processes. Asynchronous methods in C# are created using the Async
and Await keywords
42. What is Thread Pooling in C#?
In C#, a Thread Pool is a group of threads. These threads are used to do
work without interfering with the principal thread's operation.
43. Explain StreamReader/StreamWriter class?
Streamreader and StreamWriter are classes of namespace.System.IO. Used when
we want to read or write charact90, Reader based data,
respectively.
members of StreamReader are: close(), Read(), Readline().
members of Streamwriter are: close(), write(), writeline().
44. Explain Synchronous and Asynchronous Operations?
Synchronization is a way of creating a thread-safe code where only a single
thread will access the code in a given time. A synchronous call waits for
completion of method and then continous the program flow. Synchronous
programming adversely affects the UI operations that normally happens when
user tries to perform time-consuming operations since only one thread is
used.
In Asynchronous operation, the method call immediately returns allowing the
program to perform other operations while the method called completes its
share of work in certain circumstances.
Q45. Explain Async and Await
Async and Await keywords are mostly used for creating asynchronous
methods in C#. Usage of the same is shown through an example:
1
2 public async Task>CalculateCount()
{
3 await Task.Delay(2000);
4 return 1;
5 }
6 public async task mytestmethod()
{
7
Task> count = CalculateCount();
8 int result = await count;
9 }
10
46 . Explain Deadlock?
A deadlock is a situation that arises when a process isn’t able to
complete it’s execution because two or more than two processes are
waiting for each other to finish. This usually occurs in multi-threading. In
this, a shared resource is being held up by a process and another
process is waiting for the first process to get over or release it, and the
thread holding the locked item is waiting for another process to
complete.
Q47. What is Thread Pooling?
A Thread pool is a collection of threads that perform tasks without disturbing
the primary thread. Once the task is completed by a thread it returns to the
primary thread.