Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Static: Calculator

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 349

Static

In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object.
C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.

Static Class
Apply the static modifier before the class name and after the access modifier to make a class static. The following defines a static class with static fields and
methods.
public static class Calculator
{
private static int _resultStorage = 0;

public static string Type = "Arithmetic";

public static int Sum(int num1, int num2)


{
return num1 + num2;
}

public static void Store(int result)


{
_resultStorage = result;
}
}
Above, the Calculator class is a static. All the members of it are also static.
You cannot create an object of the static class; therefore the members of the static class can be accessed directly using a class name
like ClassName.MemberName, as shown below.
class Program
{
static void Main(string[] args)
{
var result = Calculator.Sum(10, 25); // calling static method
Calculator.Store(result);
var calcType = Calculator.Type; // accessing static variable
Calculator.Type = "Scientific"; // assign value to static variable
}
}

Rules for Static Class


1. Static classes cannot be instantiated.
2. All the members of a static class must be static; otherwise the compiler will give an error.
3. A static class can contain static variables, static methods, static properties, static operators, static events, and static constructors.
4. A static class cannot contain instance members and constructors.
5. Indexers and destructors cannot be static
6. var cannot be used to define static members. You must specify a type of member explicitly after the static keyword.
7. Static classes are sealed class and therefore, cannot be inherited.
8. A static class cannot inherit from other classes.
9. Static class members can be accessed using ClassName.MemberName.
10. A static class remains in memory for the lifetime of the application domain in which your program resides.

Static Members in Non-static Class


The normal class (non-static class) can contain one or more static methods, fields, properties, events and other non-static members.
It is more practical to define a non-static class with some static members, than to declare an entire class as static.

Static Fields
Static fields in a non-static class can be defined using the static keyword.
Static fields of a non-static class is shared across all the instances. So, changes done by one instance would reflect in others.
public class StopWatch
{
public static int InstanceCounter = 0;
// instance constructor
public StopWatch()
{
}
}

class Program
{
static void Main(string[] args)
{
StopWatch sw1 = new StopWatch();
StopWatch sw2 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances); //2

StopWatch sw3 = new StopWatch();


StopWatch sw4 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances);//4
}
}

Static Methods
You can define one or more static methods in a non-static class. Static methods can be called without creating an object. You cannot call static methods
using an object of the non-static class.
The static methods can only call other static methods and access static members. You cannot access non-static members of the class in the static methods.
class Program
{
static int counter = 0;
string name = "Demo Program";

static void Main(string[] args)


{
counter++; // can access static fields
Display("Hello World!"); // can call static methods

name = "New Demo Program"; //Error: cannot access non-static members


SetRootFolder("C:\MyProgram"); //Error: cannot call non-static method
}

static void Display(string text)


{
Console.WriteLine(text);
}

public void SetRootFolder(string path) { }


}

Rules for Static Methods


1. Static methods can be defined using the static keyword before a return type and after an access modifier.
2. Static methods can be overloaded but cannot be overridden.
3. Static methods can contain local static variables.
4. Static methods cannot access or call non-static variables unless they are explicitly passed as parameters.

Static Constructors
A non-static class can contain a parameterless static constructor. It can be defined with the static keyword and without access modifiers like public, private,
and protected.
The following example demonstrates the difference between static constructor and instance constructor.
public class StopWatch
{
// static constructor
static StopWatch()
{
Console.WriteLine("Static constructor called");
}

// instance constructor
public StopWatch()
{
Console.WriteLine("Instance constructor called");
}

// static method
public static void DisplayInfo()
{
Console.WriteLine("DisplayInfo called");
}

// instance method
public void Start() { }

// instance method
public void Stop() { }
}
Above, the non-static class StopWatch contains a static constructor and also a non-static constructor.
The static constructor is called only once whenever the static method is used or creating an instance for the first time. The following example shows that
the static constructor gets called when the static method called for the first time. Calling the static method second time onwards won't call a static
constructor.
StopWatch.DisplayInfo(); // static constructor called here
StopWatch.DisplayInfo(); // none of the constructors called here
Output:
Static constructor called.
DisplayInfo called
DisplayInfo called
The following example shows that the static constructor gets called when you create an instance for the first time.
StopWatch sw1 = new StopWatch(); // First static constructor and then instance constructor called
StopWatch sw2 = new StopWatch();// only instance constructor called
StopWatch.DisplayInfo();
Output:
Static constructor called
instance constructor called
instance constructor called
DisplayInfo called

Rules for Static Constructors


1. The static constructor is defined using the static keyword and without using access modifiers public, private, or protected.
2. A non-static class can contain one parameterless static constructor. Parameterized static constructors are not allowed.
3. Static constructor will be executed only once in the lifetime. So, you cannot determine when it will get called in an application if a class is being used
at multiple places.
4. A static constructor can only access static members. It cannot contain or access instance members.

Static members are stored in a special area in the memory called High-Frequency Heap. Static members of non-static classes are shared across all the
instances of the class. So, the changes done by one instance will be reflected in all the other instances.

Read Only
A Class

Static Read Only


A Class

Deep Copy and Shallow Copy


A Class

Difference between Array.Copy() and Array.Clone()


A Class

Localization and Globalization


A Class

Private
A Class
Protected
A Class

Public
A Class

Protected Internal
A Class

Internal
A Class

Yield
Yield is one of the most useful but under-used keywords in C#. The reason is that most of us don't even know about this keyword and the purpose it can
serve for us. In this article, we will be discussing this keyword to understand the basic functionality that this keyword provides.

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.

To demonstrate the use of the yield keyword, we will be creating a list with random numbers from 1-100. Our purpose will be to filter this list to get the
numbers greater than 50 (without using any temporary list). So we first create a list and add some elements to it. Next we will create a method that will
return an IEnumerator type. This will be the method in which the elements will be iterated and the result will be filtered to get the result list. We will pass
the main list to this method and get the results returned from this method. So our code will be like the following:
So what is actually happening here is that the iteration starts over the list. It checks the first value, 31, that does not matches our selection criteria. So it
continues up to fourth element in the same way, that is 53. Here, it encounters the yield statement. So what it does is that it stops the loop iteration and
returns to the calling statement again, which is the GetData function. Then after adding it to the list called _data, it returns to the loop, but this time, it
starts the operation from the next element in the list, in other words it starts processing the fifth element, 87. In this way it goes back to the calling
code again and returns to process the next element at the sixth position, 89. So it continues to iterate until the loop is completed or a break statement is
executed.

One very interesting point is related to the advantage that the yield keyword provides. It is related to how actually the state of iteration is maintained in the
entire process. Before this keyword was introduced, the entire process of managing the state of the item being processed and moving to the next item in
the process includes cumbersome code, with the use of IEnumerator interface, that was a tedious task to do. But with the introduction of the yield
keyword, we need not to be worried about how the state if the iteration to be managed. We simply need to use the yield keyword and everything else
works as needed. If you are interested in more about this process then you can try out these 2 very interesting articles that I came across C# 2.0 Iterators
and Yield Keyword - Custom Collection Enumerators and Creating and Using Custom Collection Enumerators.

Some requirements for the use of yield return


Do not put "yield" in an unsafe block.
Do not use ref or out keywords with the parameters of the method, operator or accessor (getter / setter).
"Yield return" can only be placed in the try block if it is followed by a finally block.
"Yield break" can be put in the try block and catch, but not placed in the finally block.
Do not use "yield" of the anonymous method.

Dll hell problem and how to overcome


A Class

Repository Pattern
A Class

Factory Design Pattern


A Class

Singleton Design Pattern


A Class

Encapsulation
A Class

Abstraction
A Class

Polymorphism
A Class

Runtime Polymorphism
A Class

Compile Time Polymorphism


A Class

Inheritance
A Class

Method Hiding
A Class

Virtual
A Class

Override
A Class

Early Binding
A Class

Late Binding
A Class
Static Binding
A Class

Dynamic Binding
A Class

Sealed
A Class

Event
A Class

Delegate
What if we want to pass a function as a parameter? How does C# handles the callback functions or event handler? The answer is - delegate.
The delegate is a reference type data type that defines the method signature. You can define variables of delegate, just like other data type, that can refer
to any method with the same signature as the delegate.

There are three steps involved while working with delegates:


Declare a delegate
Set a target method
Invoke a delegate

A delegate can be declared using the delegate keyword followed by a function signature, as shown below.

Delegate Syntax
[access modifier] delegate [return type] [delegate name]([parameters])
public delegate void MyDelegate(string msg);

Above, we have declared a delegate MyDelegate with a void return type and a string parameter. A delegate can be declared outside of the class or inside
the class. Practically, it should be declared out of the class.
After declaring a delegate, we need to set the target method or a lambda expression. We can do it by creating an object of the delegate using the new
keyword and passing a method whose signature matches the delegate signature.

public delegate void MyDelegate(string msg); // declare a delegate

// set target method


MyDelegate del = new MyDelegate(MethodA);
// or
MyDelegate del = MethodA;
// or set lambda expression
MyDelegate del = (string msg) => Console.WriteLine(msg);

// target method
static void MethodA(string message)
{
Console.WriteLine(message);
}
You can set the target method by assigning a method directly without creating an object of delegate e.g., MyDelegate del = MethodA.

After setting a target method, a delegate can be invoked using the Invoke() method or using the () operator.
del.Invoke("Hello World!");
// or
del("Hello World!");

The following is a full example of a delegate.


public delegate void MyDelegate(string msg); //declaring a delegate

class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
del("Hello World");
del = ClassB.MethodB;
del("Hello World");

del = (string msg) => Console.WriteLine("Called lambda expression: " + msg);


del("Hello World");
}
}

class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " + message);
}
}

class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " + message);
}
}

The following image illustrates the delegate.


Passing Delegate as a Parameter

A method can have a parameter of the delegate type, as shown below.

public delegate void MyDelegate(string msg); //declaring a delegate

class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
InvokeDelegate(del);
del = ClassB.MethodB;
InvokeDelegate(del);

del = (string msg) => Console.WriteLine("Called lambda expression: " + msg);


InvokeDelegate(del);
}

static void InvokeDelegate(MyDelegate del) // MyDelegate type parameter


{
del("Hello World");
}
}

class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " + message);
}
}

class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " + message);
}
}

In .NET, Func and Action types are built-in generic delegates that should be used for most common delegates instead of creating new custom delegates.

Multicast Delegate
The delegate can point to multiple methods. A delegate that points multiple methods is called a multicast delegate. The "+" or "+=" operator adds a
function to the invocation list, and the "-" and "-=" operator removes it.
public delegate void MyDelegate(string msg); //declaring a delegate

class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;

MyDelegate del = del1 + del2; // combines del1 + del2


del("Hello World");

MyDelegate del3 = (string msg) => Console.WriteLine("Called lambda expression: " + msg);
del += del3; // combines del1 + del2 + del3
del("Hello World");

del = del - del2; // removes del2


del("Hello World");

del -= del1 // removes del1


del("Hello World");
}
}

class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " + message);
}
}

class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " + message);
}
}
The addition and subtraction operators always work as part of the assignment: del1 += del2; is exactly equivalent to del1 = del1+del2; and likewise for
subtraction.
If a delegate returns a value, then the last assigned target method's value will be return when a multicast delegate called.

public delegate int MyDelegate(); //declaring a delegate

class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;

MyDelegate del = del1 + del2;


Console.WriteLine(del());// returns 200
}
}

class ClassA
{
static int MethodA()
{
return 100;
}
}

class ClassB
{
static int MethodB()
{
return 200;
}
}

Generic Delegate
A generic delegate can be defined the same way as a delegate but using generic type parameters or return type. The generic type must be specified
when you set a target method.
For example, consider the following generic delegate that is used for int and string parameters.
public delegate T add<T>(T param1, T param2); // generic delegate

class Program
{
static void Main(string[] args)
{
add<int> sum = Sum;
Console.WriteLine(sum(10, 20));

add<string> con = Concat;


Console.WriteLine(conct("Hello ","World!!"));
}

public static int Sum(int val1, int val2)


{
return val1 + val2;
}
public static string Concat(string str1, string str2)
{
return str1 + str2;
}
}

Delegate is also used to declare an Event and an Anonymous Method .

Points to Remember :
1. Delegate is the reference type data type that defines the signature.
2. Delegate type variable can refer to any method with the same signature as the delegate.
3. Syntax: [access modifier] delegate [return type] [delegate name]([parameters])
4. A target method's signature must match with delegate signature.
5. Delegates can be invoke like a normal function or Invoke() method.
6. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate.
7. If a multicast delegate returns a value then it returns the value from the last assigned target method.
8. Delegate is used to declare an event and anonymous methods in C#.

Action
Action is a generic delegate present in System namespace. It takes one or more input parameters and returns nothing.
So it does not return any value.

Action delegate with two input parameters.


1. Action action1=DelegateClass.ShowEmploye;
2. action1(30,"Rajesh");
3. TParameter = 30,Rajesh;
4. TOutput = Not available (No return value)

Action delegate with one input parameter.


1. Action action2=DelegateClass.ShowMessage;
2. action2("Rajesh");
3. TParameter = “Rajesh”
4. TOutput = Not available
Action delegate with Anonymous methods:
1. Action action = delegate(String msg)
2. {
3. Console.WriteLine(msg);
4. };
5. action("rajesh");
6. Action delegate with Lambda expression: Action action = (msg) =>;
7. {
8. Console.WriteLine(msg)
9. };
10. action(“Rajesh”);

Func
C# includes built-in generic delegate types Func and Action, so that you don't need to define custom delegates manually in most cases.
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is
considered as an out parameter.
The Func delegate that takes one input parameter and one out parameter is defined in the System namespace, as shown below:
namespace System
{
public delegate TResult Func<in T, out TResult>(T arg);
}
The last parameter in the angle brackets <> is considered the return type, and the remaining parameters are considered input parameter types, as
shown in the following figure.
A Func delegate with two input parameters and one out parameters will be represented as shown below.

The following Func delegate takes two input parameters of int type and returns a value of int type:
Func<int, int, int> sum;
You can assign any method to the above func delegate that takes two int parameters and returns an int value.

class Program
{
static int Sum(int x, int y)
{
return x + y;
}

static void Main(string[] args)


{
Func<int,int, int> add = Sum;

int result = add(10, 10);

Console.WriteLine(result);
}
}

Output:
20

A Func delegate type can include 0 to 16 input parameters of different types. However, it must include an out parameter for the result. For example,
the following Func delegate doesn't have any input parameter, and it includes only an out parameter.

Func with Zero input parameter


Func<int> getRandomNumber;

Func with an Anonymous Method


You can assign an anonymous method to the Func delegate by using the delegate keyword.

Func<int> getRandomNumber = delegate()


{
Random rnd = new Random();
return rnd.Next(1, 100);
};

Func with Lambda Expression


A Func delegate can also be used with a lambda expression, as shown below:
Func<int> getRandomNumber = () => new Random().Next(1, 100);
//Or
Func<int, int, int> Sum = (x, y) => x + y;
Points to Remember :
1. Func is built-in delegate type.
2. Func delegate type must return a value.
3. Func delegate type can have zero to 16 input parameters.
4. Func delegate does not allow ref and out parameters.
5. Func delegate type can be used with an anonymous method or lambda expression.

Predicate
Predicate delegate is also inbuilt generic delegate and is present in System namespace.
It is used to verify certain criteria of method and returns output as Boolean, either True or False.
Predicate can be used with method, anonymous and lambda expression.

Check String value is number using Predicate delegates.


Predicate predicate = DelegateClass.IsNumeric;
bool number = predicate("1234");

Predicate delegate using Anonymous method.


1. Predicate predicate = delegate(string str)
2. {
3. double retNum;
4. bool isNum = Double.TryParse(Convert.ToString(str), System.Globalization.NumberStyles.Any, Syste
m.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
5. return isNum;
6. };
7. bool found = predicate("12232");

Predicate delegate using lambda expression.


1. Predicate predicate = (str) =>;
2. {
3. double retNum;
4. bool isNum = Double.TryParse(Convert.ToString(str), System.Globalization.NumberStyles.Any, Syste
m.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
5. return isNum;
6. };
7. bool found = predicate("12232");

Delegate vs Event
The following table lists the difference between the delegate and the event in C#.
Delegate Event

A delegate is declared using the delegate An event is declared using the event keyword.
keyword.

Delegate is a function pointer. It holds The event is a notification mechanism that depends on delegates
the reference of one or more methods at
runtime.

Delegate is independent and not An event is dependent on a delegate and cannot be created without delegates. Event is a
dependent on events. wrapper around delegate instance to prevent users of the delegate from resetting the
delegate and its invocation list and only allows adding or removing targets from the invocation
list.

Delegate includes Combine() and EventInfo class inspect events and to hook up event handlers that include methods
Remove() methods to add methods to AddEventHandler() and RemoveEventHandler() methods to add and remove methods to
the invocation list. invocation list, respectively.

A delegate can be passed as a method An event is raised but cannot be passed as a method parameter.
parameter.

= operator is used to assigning a single = operator cannot be used with events, and only += and -= operator can be used with an event
method, and += operator is used to that adds or remove event handler. These methods internally call AddEventHandler and
assign multiple methods to a delegate. RemoveEventHandler methods.
In a way, an event is a delegate only. The program code will work even if you remove the event keyword and only use a delegate. However, using the event
keyword, we prevent subscribers to register with an event by using = operator and thereby removing all handlers.

Consider the following example.


public delegate void Notify();
public Notify MyDelegate;

MyDelegate = MyMethod;// valid


MyDelegate += MyMethod;// valid

public delegate void Notify();


public event Notify MyEvent;

MyEvent = MyEventHandler;// Error


MyEvent += MyEventHandler;// valid

Indexer
A Class

IEnumerable
IEnumerable is the base interface for all non-generic collections that can be enumerated. For the generic version of this interface
see System.Collections.Generic.IEnumerable<T>. IEnumerable contains a single method, GetEnumerator, which returns
an IEnumerator. IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.

It is a best practice to implement IEnumerable and IEnumerator on your collection classes to enable the foreach (For Each in Visual Basic) syntax, however
implementing IEnumerable is not required. If your collection does not implement IEnumerable, you must still follow the iterator pattern to support this
syntax by providing a GetEnumerator method that returns an interface, class or struct. When using Visual Basic, you must provide
an IEnumerator implementation, which is returned by GetEnumerator. When developing with C# you must provide a class that contains a Current property,
and MoveNext and Reset methods as described by IEnumerator, but the class does not have to implement IEnumerator.

IEnumerator
IEnumerator is the base interface for all non-generic enumerators. Its generic equivalent is the System.Collections.Generic.IEnumerator<T> interface.
The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended
instead of directly manipulating the enumerator.

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

The Reset method is provided for COM interoperability and does not need to be fully implemented; instead, the implementer can throw
a NotSupportedException.

Initially, the enumerator is positioned before the first element in the collection. You must call the MoveNext method to advance the enumerator to the first
element of the collection before reading the value of Current; otherwise, Current is undefined.

Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element.

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the
enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, Current is undefined.

To set Current to the first element of the collection again, you can call Reset, if it's implemented, followed by MoveNext. If Reset is not implemented, you
must create a new enumerator instance to return to the first element of the collection.

If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure.
Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee
thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by
other threads.

IQueryable
A Class

Linq
A Class
Dictionary
A Class

Threading
A Class

Lock
A Class

Monitor
A Class

Mutex
A Class

Difference between Lock and Monitor


The Monitor class allows you to synchronize access to a region of code by taking and releasing a lock on a particular object by calling
the Monitor.Enter, Monitor.TryEnter, and Monitor.Exit methods. Object locks provide the ability to restrict access to a block of code, commonly called a
critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use the Monitor class to ensure that no other
thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different
locked object.

Difference between Task and Thread


A Class

Async & Await


A Class

SynchronizationContext
A Class
ThreadPool
Thread pooling is the process of creating a collection of threads during the initialization of a multithreaded application, and then reusing
those threads for new tasks as and when required, instead of creating new threads. Then every process has some fixed number of
threads depending on the amount of memory available, those threads are the need of the application but we have freedom to increase
the number of threads. Every thread in the pool has a specific given task. The thread returns to the pool and waits for the next
assignment when the given task is completed.

Usually, the thread pool is required when we have number of threads are created to perform a number of tasks, in this organized in a
queue. Typically, we have more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue
until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available.

Creating thread pooling

The .Net framework library included the "System.Threading.ThreadPool" class. it was so easy to use.You need not create the pool of
threads, nor do you have to specify how many consuming threads you require in the pool. The ThreadPool class handles the creation of
new threads and the distribution of the wares to consume amongst those threads.

There are a number of ways to create the thread pool:


 Via the Task Parallel Library (from Framework 4.0).
 By calling ThreadPool.QueueUserWorkItem.
 Via asynchronous delegates.
 Via BackgroundWorker.

Entering the Thread Pool via TPL

The task parallel library provide the task class for enter the thread pool easy. The task class is the part of .Net Framework 4.0 .if you're
familiar with the older constructs, consider the nongeneric Task class a replacement for ThreadPool.QueueUserWorkItem, and the generic
Task<TResult> a replacement for asynchronous delegates. The newer constructs are faster, more convenient, and more flexible than the
old.

To use the nongeneric Task class, call Task.Factory.StartNew, ing in a delegate of the target method:

using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System;

class Akshay
{
static void Run()
{
Console.WriteLine("Welcome to the C# corner thread pool!");
}
static void Main() // The Task class is in System.Threading.Tasks
{
Task.Factory.StartNew(Run);
Console.Read();
}
}

Output :
Task.Factory.StartNew returns a Task object, which you can then use to monitor the task-for instance, you can wait for it to complete by
calling its Wait method.

The generic Task<TResult> class is a subclass of the nongeneric Task. It lets you get a return value back from the task after it finishes
executing. In the following example, we download a web page using Task<TResult>:

class Akshay
{
static void Main()
{
// Start the task executing:
Task<string> task = Task.Factory.StartNew<string>
(() => DownloadString("http://www.c-sharpcorner.com/"));
// We can do other work here and it will execute in parallel:
//RunSomeOtherMethod();
// When we need the task's return value, we query its Result property:
// If it's still executing, the current thread will now block (wait)
// until the task finishes:
string result = task.Result;
}
static string DownloadString(string uri)
{
using (var wc = new System.Net.WebClient())
return wc.DownloadString(uri);
Console.Read();
}
}

Entering the Thread Pool Without TPL using ThreadPool.QueueUserWorkItem

You can't use the Task Parallel Library if you're targeting an earlier version of the .NET Framework (prior to 4.0). Instead, you must use
one of the older constructs for entering the thread pool: ThreadPool.QueueUserWorkItem and asynchronous delegates.

The ThreadPool.QueueUserWorkItem method allows us to launch the execution of a function on the system thread pool. Its declaration is
as follows:

ThreadPool.QueueUserWorkItem(new WaitCallback(Consume), ware);

The first parameter specifies the function that we want to execute on the pool. Its signature must match the delegate WaitCallback.

publicdelegate void WaitCallback (object state);

Again, the simplicity of C# and the dotNet framework shine through. In just a few lines of code, I've recreated a multithreaded
consumer-producer application.

using System;
using System.Threading;
using System.Diagnostics;
public class Akshay
{
public int id;
public Akshay(int _id)
{
id = _id;
}
}
class Class1
{
public int QueueLength;
public Class1()
{
QueueLength = 0;
}
public void Produce(Akshay ware)
{
ThreadPool.QueueUserWorkItem(
new WaitCallback(Consume), ware);
QueueLength++;
}
public void Consume(Object obj)
{
Console.WriteLine("Thread {0} consumes {1}",
Thread.CurrentThread.GetHashCode(), //{0}
((Akshay)obj).id); //{1}
Thread.Sleep(100);
QueueLength--;
}
public static void Main(String[] args)
{
Class1 obj = new Class1();
for (int i = 0; i < 100; i++)
{
obj.Produce(new Akshay(i));
}
Console.WriteLine("Thread {0}",
Thread.CurrentThread.GetHashCode() ); //{0}
while (obj.QueueLength != 0)
{
Thread.Sleep(1000);
}
Console.Read();
}
}

Ouput :

Synchronization Objects

The previous code contains some rather inefficient coding when the main thread cleans up. I repeatedly test the queue length every
second until the queue length reaches zero. This may mean that the process will continue executing for up to a full second after the
queues are finally drained. I can't have that.

The following example uses a ManualResetEvent Event object that will signal the main thread to exit.
using System;
using System.Threading;
using System.Diagnostics;
public class Akshay
{
private bool WaitForComplete;
private ManualResetEvent Event;
public int QueueLength;
public int id;
public Akshay(int _id)
{
id = _id;
}
public void Wait()
{
if (QueueLength == 0)
{
return;
}
Event = new ManualResetEvent(false);
WaitForComplete = true;
Event.WaitOne();
}
public void Consume(Object obj)
{
Console.WriteLine("Thread {0} consumes {1}",
Thread.CurrentThread.GetHashCode(), //{0}
((Akshay)obj).id); //{1}
Thread.Sleep(100);
QueueLength--;
if (WaitForComplete)
{
if (QueueLength == 0)
{
Event.Set();
}
};
}
}

Ouput :

When the consuming thread finishes consuming a ware and detects that the WaitForComplete is true, it will trigger the Event when the
queue length is zero. Instead of calling the while block when it wants to exit, the main thread calls the Wait instance method. This
method sets the WaitForComplete flag and waits on the Event object.

Why we need thread pooling?


Thread pooling is essential in multithreaded applications for the following reasons.
 Thread pooling improves the response time of an application as threads are already available in the thread pool waiting for their
next assignment and do not need to be created from scratch.
 Thread pooling saves the CLR from the overhead of creating an entirely new thread for every short-lived task and reclaiming its
resources once it dies.
 Thread pooling optimizes the thread time slices according to the current process running in the system.
 Thread pooling enables us to start several tasks without having to set the properties for each thread.
 Thread pooling enables us to state information as an object to the procedure arguments of the task that is being executed.
 Thread pooling can be employed to fix the maximum number of threads for processing a particular request.

ReactiveX
Thread

Task Parallel Library


The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces. The purpose of the TPL is
to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL scales the degree of
concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the
scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details. By using TPL, you can maximize the
performance of your code while focusing on the work that your program is designed to accomplish.

Starting with .NET Framework 4, the TPL is the preferred way to write multithreaded and parallel code. However, not all code is suitable for parallelization.
For example, if a loop performs only a small amount of work on each iteration, or it doesn't run for many iterations, then the overhead of parallelization can
cause the code to run more slowly. Furthermore, parallelization like any multithreaded code adds complexity to your program execution. Although the TPL
simplifies multithreaded scenarios, we recommend that you have a basic understanding of threading concepts, for example, locks, deadlocks, and race
conditions, so that you can use the TPL effectively.

Data parallelism
Data parallelism refers to scenarios in which the same operation is performed concurrently (that is, in parallel) on elements in a source collection or array.
In data parallel operations, the source collection is partitioned so that multiple threads can operate on different segments concurrently.

The Task Parallel Library (TPL) supports data parallelism through the System.Threading.Tasks.Parallel class. This class provides method-based parallel
implementations of for and foreach loops (For and For Each in Visual Basic). You write the loop logic for a Parallel.For or Parallel.ForEach loop much as you
would write a sequential loop. You do not have to create threads or queue work items. In basic loops, you do not have to take locks. The TPL handles all the
low-level work for you. For in-depth information about the use of Parallel.For and Parallel.ForEach, download the document Patterns for Parallel
Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4. The following code example shows a simple foreach loop and its
parallel equivalent.
// Sequential version
for (int i = 0; i < matARows; i++)
{
for (int j = 0; j < matBCols; j++)
{
double temp = 0;
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
result[i, j] += temp;
}
}

// Parallel equivalent
Parallel.For(0, matARows, i =>
{
for (int j = 0; j < matBCols; j++)
{
double temp = 0;
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
result[i, j] = temp;
}
});

// Sequential version
foreach (var item in sourceCollection)
{
Process(item);
}

// Parallel equivalent
Parallel.ForEach(sourceCollection, item => Process(item));
Both the Parallel.For and Parallel.ForEach methods have several overloads that let you stop or break loop execution, monitor the state of the loop on other
threads, maintain thread-local state, finalize thread-local objects, control the degree of concurrency, and so on. The helper types that enable this
functionality include ParallelLoopState, ParallelOptions, ParallelLoopResult, CancellationToken, and CancellationTokenSource.
For more information, see Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4.

Data parallelism with declarative, or query-like, syntax is supported by PLINQ. For more information, see Parallel LINQ (PLINQ).

Parallel.For(Int64, Int64, Action<Int64>) method overload and Parallel.For(Int32, Int32, Action<Int32>) method overload

// Sequential version
for (int i = 0; i < matARows; i++)
{
for (int j = 0; j < matBCols; j++)
{
double temp = 0;
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
result[i, j] += temp;
}
}

// Parallel equivalent
Parallel.For(0, matARows, i =>
{
for (int j = 0; j < matBCols; j++)
{
double temp = 0;
for (int k = 0; k < matACols; k++)
{
temp += matA[i, k] * matB[k, j];
}
result[i, j] = temp;
}
});

When parallelizing any code, including loops, one important goal is to utilize the processors as much as possible without over parallelizing to the point
where the overhead for parallel processing negates any performance benefits. In this particular example, only the outer loop is parallelized because there is
not very much work performed in the inner loop. The combination of a small amount of work and undesirable cache effects can result in performance
degradation in nested parallel loops. Therefore, parallelizing the outer loop only is the best way to maximize the benefits of concurrency on most systems.

The Delegate
The third parameter of this overload of For is a delegate of type Action<int> in C# or Action(Of Integer) in Visual Basic. An Action delegate, whether it has
zero, one or sixteen type parameters, always returns void. In Visual Basic, the behavior of an Action is defined with a Sub. The example uses a lambda
expression to create the delegate, but you can create the delegate in other ways as well. For more information, see Lambda Expressions in PLINQ and TPL.

The Iteration Value


The delegate takes a single input parameter whose value is the current iteration. This iteration value is supplied by the runtime and its starting value is the
index of the first element on the segment (partition) of the source that is being processed on the current thread.
If you require more control over the concurrency level, use one of the overloads that takes a System.Threading.Tasks.ParallelOptions input parameter, such
as: Parallel.For(Int32, Int32, ParallelOptions, Action<Int32,ParallelLoopState>).

Return Value and Exception Handling


For returns a System.Threading.Tasks.ParallelLoopResult object when all threads have completed. This return value is useful when you are stopping or
breaking loop iteration manually, because the ParallelLoopResult stores information such as the last iteration that ran to completion. If one or more
exceptions occur on one of the threads, a System.AggregateException will be thrown.
In the code in this example, the return value of For is not used.

Abstract Class
SOLID Principles
There are five SOLID principles:
 Single Responsibility Principle (SRP)
 Open Closed Principle (OCP)
 Liskov Substitution Principle (LSP)
 Interface Segregation Principle (ISP)
 Dependency Inversion Principle (DIP)

Single Responsibility Principle (SRP)


Definition: A class should have only one reason to change.
In layman terminology, this means that a class should not be loaded with multiple responsibilities and a single responsibility should
not be spread across multiple classes or mixed with other responsibilities. The reason is that more changes requested in the future,
the more changes the class need to apply.

Understanding
Single Responsibility Principle is one of the five SOLID principles which guide developers as they write code or design an
application.
In simple terms, a module or class should have a very small piece of responsibility in the entire application. Or as it states, a
class/module should have not more than one reason to change.
If a class has only a single responsibility, it is likely to be very robust. It’s easy to verify its working as per logic defined. And it’s easy
to change in class as it has single responsibility.
The Single Responsibility Principle provides another benefit. Classes, software components and modules that have only one
responsibility are much easier to explain, implement and understand than ones that give a solution for everything.
This also reduces number of bugs and improves development speed and most importantly makes developer’s life lot easier.

Implementation
Let’s take a scenario of Garage service station functionality. It has 3 main functions; open gate, close gate and performing service.
Below example violates SRP principle. The code below, violates SRP principle as it mixes open gate and close gate responsibilities
with the main function of servicing of vehicle.
public class GarageStation
{
public void DoOpenGate()
{
//Open the gate functinality
}

public void PerformService(Vehicle vehicle)


{
//Check if garage is opened
//finish the vehicle service
}

public void DoCloseGate()


{
//Close the gate functinality
}
}

We can correctly apply SRP by refactoring of above code by introducing interface. A new interface called IGarageUtility is created
and gate related methods are moved to different class called GarageStationUtility.
public class GarageStation
{
IGarageUtility _garageUtil;

public GarageStation(IGarageUtility garageUtil)


{
this._garageUtil = garageUtil;
}

public void OpenForService()


{
_garageUtil.OpenGate();
}

public void DoService()


{
//Check if service station is opened and then
//finish the vehicle service
}

public void CloseGarage()


{
_garageUtil.CloseGate();
}
}

public class GarageStationUtility : IGarageUtility


{
public void OpenGate()
{
//Open the Garage for service
}

public void CloseGate()


{
//Close the Garage functionlity
}
}

public interface IGarageUtility


{
void OpenGate();
void CloseGate();
}

Open Closed Principle (OCP)


Definition: Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

Understanding
This principle suggests that the class should be easily extended but there is no need to change its core implementations.
The application or software should be flexible to change. How change management is implemented in a system has a significant
impact on the success of that application/ software. The OCP states that the behaviors of the system can be extended without
having to modify its existing implementation.
i.e. New features should be implemented using the new code, but not by changing existing code. The main benefit of adhering to
OCP is that it potentially streamlines code maintenance and reduces the risk of breaking the existing implementation.

Implementation
Let’s take an example of bank accounts like regular savings, salary saving, corporate etc. for different customers. As for each
customer type, there are different rules and different interest rates. The code below violates OCP principle if the bank introduces a
new Account type. Said code modifies this method for adding a new account type.
public class Account
{
public decimal Interest { get; set; }
public decimal Balance { get; set; }

// members and function declaration


public decimal CalcInterest(string accType)
{
if (accType == "Regular") // savings
{
Interest = (Balance * 4) / 100;
if (Balance < 1000) Interest -= (Balance * 2) / 100;
if (Balance < 50000) Interest += (Balance * 4) / 100;
}
else if (accType == "Salary") // salary savings
{
Interest = (Balance * 5) / 100;
}
else if (accType == "Corporate") // Corporate
{
Interest = (Balance * 3) / 100;
}
return Interest;
}
}

We can apply OCP by using interface, abstract class, abstract methods and virtual methods when you want to extend functionality.
Here I have used interface for example only but you can go as per your requirement.
interface IAccount
{
// members and function declaration, properties
decimal Balance { get; set; }
decimal CalcInterest();
}

//regular savings account


public class RegularSavingAccount : IAccount
{
public decimal Balance { get; set; } = 0;
public decimal CalcInterest()
{
decimal Interest = (Balance * 4) / 100;
if (Balance < 1000) Interest -= (Balance * 2) / 100;
if (Balance < 50000) Interest += (Balance * 4) / 100;

return Interest;
}
}

//Salary savings account


public class SalarySavingAccount : IAccount
{
public decimal Balance { get; set; } = 0;
public decimal CalcInterest()
{
decimal Interest = (Balance * 5) / 100;
return Interest;
}
}

//Corporate Account
public class CorporateAccount : IAccount
{
public decimal Balance { get; set; } = 0;
public decimal CalcInterest()
{
decimal Interest = (Balance * 3) / 100;
return Interest;
}
}
In the above code three new classes are created; regular saving account, SalarySavingAccount, and CorporateAccount, by extending
them from IAccount.
This solves the problem of modification of class and by extending interface, we can extend functionality.
Above code is implementing both OCP and SRP principle, as each class has single is doing a single task and we are not modifying
class and only doing an extension.

Liskov Substitution Principle (LSP)


Definition by Robert C. Martin: Functions that use pointers or references to base classes must be able to use objects of derived
classes without knowing it.

Understanding
LSP states that the child class should be perfectly substitutable for their parent class. If class C is derived from P then C should be
substitutable for P.
We can check using LSP that inheritance is applied correctly or not in our code.
LSP is a fundamental principle of SOLID Principles and states that if program or module is using base class then derived class should
be able to extend their base class without changing their original implementation.

Implementation
Let’s consider the code below where LSP is violated. We cannot simply substitute a Triangle, which results in printing shape of a
triangle, with Circle.
namespace Demo
{
public class Program
{
static void Main(string[] args)
{
Triangle triangle = new Circle();
Console.WriteLine(triangle.GetColor());
}
}
public class Triangle
{
public virtual string GetShape()
{
return " Triangle ";
}
}

public class Circle : Triangle


{
public override string GetShape()
{
return "Circle";
}
}
}

To correct above implementation, we need to refactor this code by introducing interface with method called GetShape.
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Shape shape = new Circle();
Console.WriteLine(shape.GetShape());
shape = new Triangle ();
Console.WriteLine(shape.GetShape());
}
}

public abstract class Shape


{
public abstract string GetShape();
}

public class Triangle: Shape


{
public override string GetShape()
{
return "Triangle";
}
}

public class Circle : Shape


{
public override string GetShape()
{
return "Circle";
}
}
}

Interface Segregation Principle (ISP)


Definition: No client should be forced to implement methods which it does not use, and the contracts should be broken down to
this ones.

Understanding
Interface segregation principle is required to solve the design problem of the application. When all the tasks are done by a single
class or in other words, one class is used in almost all the application classes then it has become a fat class with overburden.
Inheriting such class will results in having sharing methods which are not relevant to derived classes but its there in the base class
so that will inherit in the derived class.
Using ISP, we can create separate interfaces for each operation or requirement rather than having a single class to do the same
work.
Implementation
In below code, ISP is broken as process method is not required by OfflineOrder class but is forced to implement.
public interface IOrder
{
void AddToCart();
void CCProcess();
}

public class OnlineOrder : IOrder


{
public void AddToCart()
{
//Do Add to Cart
}

public void CCProcess()


{
//process through credit card
}
}

public class OfflineOrder : IOrder


{
public void AddToCart()
{
//Do Add to Cart
}

public void CCProcess()


{
//Not required for Cash/ offline Order
throw new NotImplementedException();
}
}

We can resolve this violation by dividing IOrder Interface.


public interface IOrder
{
void AddToCart();
}

public interface IOnlineOrder


{
void CCProcess();
}

public class OnlineOrder : IOrder, IOnlineOrder


{
public void AddToCart()
{
//Do Add to Cart
}

public void CCProcess()


{
//process through credit card
}
}

public class OfflineOrder : IOrder


{
public void AddToCart()
{
//Do Add to Cart
}
}

Dependency Inversion Principle (DIP)


This principle is about dependencies among components. The definition of DIP is given by Robert C. Martin is as follows:
1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
2. Abstractions should not depend on details. Details should depend on abstractions.

Understanding
The principle says that high-level modules should depend on abstraction, not on the details, of low-level modules. In simple words,
the principle says that there should not be a tight coupling among components of software and to avoid that, the components
should depend on abstraction.
The terms Dependency Injection (DI) and Inversion of Control (IoC) are generally used as interchangeably to express the same
design pattern.
Inversion of Control (IoC) is a technique to implement the Dependency Inversion Principle in C#. Inversion of control can be
implemented using either an abstract class or interface. The rule is that the lower level entities should join the contract to a single
interface and the higher-level entities will use only entities that are implementing the interface. This technique removes the
dependency between the entities.

Note:
In below implementation, I have used interface as a reference, but you can use abstract class or interface as per your requirement.

Implementation
In below code, we have implemented DIP using IoC using injection constructor. There are different ways to implement Dependency
injection. Here, I have use injection through constructor but you inject the dependency into class's constructor (Constructor
Injection), set property (Setter Injection), method (Method Injection), events, index properties, fields and basically any members of
the class which are public.
public interface IAutomobile
{
void Ignition();
void Stop();
}

public class Jeep : IAutomobile


{
#region IAutomobile Members
public void Ignition()
{
Console.WriteLine("Jeep start");
}

public void Stop()


{
Console.WriteLine("Jeep stopped.");
}
#endregion
}

public class SUV : IAutomobile


{
#region IAutomobile Members
public void Ignition()
{
Console.WriteLine("SUV start");
}

public void Stop()


{
Console.WriteLine("SUV stopped.");
}
#endregion
}

public class AutomobileController


{
IAutomobile m_Automobile;

public AutomobileController(IAutomobile automobile)


{
this.m_Automobile = automobile;
}

public void Ignition()


{
m_Automobile.Ignition();
}

public void Stop()


{
m_Automobile.Stop();
}
}

class Program
{
static void Main(string[] args)
{
IAutomobile automobile = new Jeep();
//IAutomobile automobile = new SUV();
AutomobileController automobileController = new AutomobileController(automobile);
automobile.Ignition();
automobile.Stop();

Console.Read();
}
}
In the above code, IAutomobile interface is in an abstraction layer and AutomobileController as the higher-level module. Here, we
have integrated all in a single code but in real-world, each abstraction layer is a separate class with additional functionality. Here
products are completely decoupled from the consumer using IAutomobile interface. The object is injected into the constructor of
the AutomobileController class in reference to the interface IAutomobile. The constructor where the object gets injected is called
injection constructor.
DI is a software design pattern that allows us to develop loosely coupled code. Using DI, we can reduce tight coupling between software
components. DI also allows us to better accomplish future changes and other difficulties in our software. The purpose of DI is to make code
sustainable.
Read More Articles Related to Design patterns

Conclusion
The five solid principles discussed above is good for Object Oriented design. Most of the principles involved are adding a layer of
abstraction between classes that would otherwise dependent on each other, thus creating a loose coupling relationship which
results in less rigid and fragile code. It is always recommended to keep these principles in mind when writing new code.

What are design patterns?


Design patterns are documented tried and tested solutions for recurring problems in a given context. So basically you have a
problem context and the proposed solution for the same. Design patterns existed in some or other form right from the
inception stage of software development. Let's say if you want to implement a sorting algorithm the first thing comes to
mind is bubble sort. So the problem is sorting and solution is bubble sort. Same holds true for design patterns.

Which are the three main categories of design patterns?


There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

Creational Patterns

Abstract Factory : Creates an instance of several families of classes


Builder : Separates object construction from its representation
Factory Method : Creates an instance of several derived classes
Prototype : A fully initialized instance to be copied or cloned
Singleton : A class in which only a single instance can exist

Note

The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First President of States).

Structural Patterns

Adapter : Match interfaces of different classes .


Bridge : Separates an object's abstraction from its implementation.
Composite : A tree structure of simple and composite objects.
Decorator : Add responsibilities to objects dynamically.
Flyweight : A fine-grained instance used for efficient sharing.
Proxy : An object representing another object.

Note

To remember structural pattern best is (ABCDFFP)

Behavioral Patterns

Mediator : Defines simplified communication between classes.


Memento : Capture and restore an object's internal state.
Interpreter : A way to include language elements in a program.
Iterator : Sequentially access the elements of a collection.
Chain of Resp : A way of passing a request between a chain of objects.
Command : Encapsulate a command request as an object.
State : Alter an object's behavior when its state changes.
Strategy : Encapsulates an algorithm inside a class.
Observer : A way of notifying change to a number of classes.
Template Method : Defer the exact steps of an algorithm to a subclass.
Visitor : Defines a new operation to a class without change.

Note: Just remember Music....... 2 MICS On TV (MMIICCSSOTV).

Note : In the further section we will be covering all the above design patterns in a more detail manner.

Can you explain factory pattern?


Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it's meant to
construct and create something. In software architecture world factory pattern is meant to centralize creation of objects.
Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice
type specified by the client. There are two issues with the code below :

First we have lots of 'new' keyword scattered in the client. In other ways the client is loaded with lot of object creational
activities which can make the client logic very complicated.

Second issue is that the client needs to be aware of all types of invoices. So if we are adding one more invoice class type
called as 'InvoiceWithFooter' we need to reference the new class in the client and recompile the client also.
Figure 1. Different types of invoice

Taking these issues as our base we will now look in to how factory pattern can help us solve the same. Below figure 'Factory
Pattern' shows two concrete classes 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader'.

The first issue was that these classes are in direct contact with client which leads to lot of 'new' keyword scattered in the client
code. This is removed by introducing a new class 'ClsFactoryInvoice' which does all the creation of objects.

The second issue was that the client code is aware of both the concrete classes i.e. 'ClsInvoiceWithHeader' and
'ClsInvoiceWithOutHeader'. This leads to recompiling of the client code when we add new invoice types. For instance if we
add 'ClsInvoiceWithFooter' client code needs to be changed and recompiled accordingly. To remove this issue we have
introduced a common interface 'IInvoice'. Both the concrete classes 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader'
inherit and implement the 'IInvoice' interface.

The client references only the 'IInvoice' interface which results in zero connection between client and the concrete classes
( 'ClsInvoiceWithHeader' and 'ClsInvoiceWithOutHeader'). So now if we add new concrete invoice class we do not need to
change any thing at the client side.

In one line the creation of objects is taken care by 'ClsFactoryInvoice' and the client disconnection from the concrete classes
is taken care by 'IInvoice' interface.

Figure 2. Factory pattern

Below are the code snippets of how actually factory pattern can be implemented in C#. In order to avoid recompiling the
client we have introduced the invoice interface 'IInvoice'. Both the concrete classes 'ClsInvoiceWithOutHeaders' and
'ClsInvoiceWithHeader' inherit and implement the 'IInvoice' interface.
Figure 3. Interface and concrete classes

We have also introduced an extra class 'ClsFactoryInvoice' with a function 'getInvoice()' which will generate objects of both
the invoices depending on 'intInvoiceType' value. In short we have centralized the logic of object creation in the
'ClsFactoryInvoice'. The client calls the 'getInvoice' function to generate the invoice classes. One of the most important points
to be noted is that client only refers to 'IInvoice' type and the factory class 'ClsFactoryInvoice' also gives the same type of
reference. This helps the client to be complete detached from the concrete classes, so now when we add new classes and
invoice types we do not need to recompile the client.
Figure 4. Factory class which generates objects
Note : The above example is given in C# . Even if you are from some other technology you can still map the concept
accordingly. You can get source code from the CD in 'FactoryPattern' folder.

Can you explain abstract factory pattern?


Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to
one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which
unifies them in a common class. All other things related to factory pattern remain same as discussed in the previous
question.

A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between
related factory patterns which leads more simplified interface for the client.

Figure 5. Abstract factory unifies related factory patterns

Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As
said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory
(AbstractFactory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from
common interface. For instance in figure 'Implementation of abstract factory' both the concrete classes 'product1' and
'product2' inherits from one interface i.e. 'common'. The client who wants to use the concrete class will only interact with the
abstract factory and the common interface from which the concrete classes inherit.

Figure 6. Implementation of abstract factory

Now let's have a look at how we can practically implement abstract factory in actual code. We have scenario where we have
UI creational activities for textboxes and buttons through their own centralized factory classes 'ClsFactoryButton' and
'ClsFactoryText'. Both these classes inherit from common interface 'InterfaceRender'. Both the factories 'ClsFactoryButton'
and 'ClsFactoryText' inherits from the common factory 'ClsAbstractFactory'. Figure 'Example for AbstractFactory' shows how
these classes are arranged and the client code for the same. One of the important points to be noted about the client code is
that it does not interact with the concrete classes. For object creation it uses the abstract factory ( ClsAbstractFactory ) and
for calling the concrete class implementation it calls the methods via the interface 'InterfaceRender'. So the
'ClsAbstractFactory' class provides a common interface for both factories 'ClsFactoryButton' and 'ClsFactoryText'.
Figure 7. Example for abstract factory

Note: We have provided a code sample in C# in the 'AbstractFactory' folder. People who are from different technology can
compare easily the implementation in their own language.

We will just run through the sample code for abstract factory. Below code snippet 'Abstract factory and factory code snippet'
shows how the factory pattern classes inherit from abstract factory.
Figure 8. Abstract factory and factory code snippet

Figure 'Common Interface for concrete classes' how the concrete classes inherits from a common interface 'InterFaceRender'
which enforces the method 'render' in all the concrete classes.

Figure 9. Common interface for concrete classes

The final thing is the client code which uses the interface 'InterfaceRender' and abstract factory 'ClsAbstractFactory' to call
and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes.
Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.
Figure 10. Client, interface and abstract factory

Can you explain prototype pattern?


Prototype pattern falls in the section of creational pattern. It gives us a way to create new objects from the existing instance
of the object. In one sentence we clone the existing object with its data. By cloning any changes to the cloned object does not
affect the original object value. If you are thinking by just setting objects we can get a clone then you have mistaken it. By
setting one object to other object we set the reference of object BYREF. So changing the new object also changed the original
object. To understand the BYREF fundamental more clearly consider the figure 'BYREF' below. Following is the sequence of
the below code:

 In the first step we have created the first object i.e. obj1 from class1.

 In the second step we have created the second object i.e. obj2 from class1.
 In the third step we set the values of the old object i.e. obj1 to 'old value'.

 In the fourth step we set the obj1 to obj2.

 In the fifth step we change the obj2 value.

 Now we display both the values and we have found that both the objects have the new value.

Figure 21. BYREF

The conclusion of the above example is that objects when set to other objects are set BYREF. So changing new object values
also changes the old object value.

There are many instances when we want the new copy object changes should not affect the old object. The answer to this is
prototype patterns.

Lets look how we can achieve the same using C#. In the below figure 'Prototype in action' we have the customer class
'ClsCustomer' which needs to be cloned. This can be achieved in C# my using the 'MemberWiseClone' method. In JAVA we
have the 'Clone' method to achieve the same. In the same code we have also shown the client code. We have created two
objects of the customer class 'obj1' and 'obj2'. Any changes to 'obj2' will not affect 'obj1' as it's a complete cloned copy.

Figure 22. Prototype in action

Note : You can get the above sample in the CD in 'Prototype' folder. In C# we use the 'MemberWiseClone' function while in
JAVA we have the 'Clone' function to achieve the same.
Can you explain shallow copy and deep copy in prototype patterns?
There are two types of cloning for prototype patterns. One is the shallow cloning which you have just read in the first
question. In shallow copy only that object is cloned, any objects containing in that object is not cloned. For instance consider
the figure 'Deep cloning in action' we have a customer class and we have an address class aggregated inside the customer
class. 'MemberWiseClone' will only clone the customer class 'ClsCustomer' but not the 'ClsAddress' class. So we added the
'MemberWiseClone' function in the address class also. Now when we call the 'getClone' function we call the parent cloning
function and also the child cloning function, which leads to cloning of the complete object. When the parent objects are
cloned with their containing objects it's called as deep cloning and when only the parent is clones its termed as shallow
cloning.
Figure 23. Deep cloning in action

Can you explain singleton pattern?


There are situations in a project where we want only one instance of the object to be created and shared between the
clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared
across the clients. Below are the steps to make a singleton pattern :-

1. Define the constructor as private.

2. Define the instances and methods as static.

Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instance and
methods using the static keyword as shown in the below code snippet figure 'Singleton in action'. The static keyword ensures
that you only one instance of the object is created and you can all the methods of the class without creating the object. As we
have made the constructor private, we need to call the class directly.
Figure 24. Singleton in action

Note : In JAVA to create singleton classes we use the STATIC keyword , so its same as in C#. You can get a sample C# code for
singleton in the 'singleton' folder.

Can you explain command patterns?


Command pattern allows a request to exist as an object. Ok let's understand what it means. Consider the figure 'Menu and
Commands' we have different actions depending on which menu is clicked. So depending on which menu is clicked we have
passed a string which will have the action text in the action string. Depending on the action string we will execute the action.
The bad thing about the code is it has lot of 'IF' condition which makes the coding more cryptic.
Figure 25. Menu and Commands

Command pattern moves the above action in to objects. These objects when executed actually execute the command.

As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and
print. Al l the above actions are wrapped in to classes like Exit action is wrapped in 'clsExecuteExit' , open action is wrapped
in 'clsExecuteOpen', print action is wrapped in 'clsExecutePrint' and so on. All these classes are inherited from a common
interface 'IExecute'.
Figure 26. Objects and Command

Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes
which have the action.

So we have added all the actions in one collection i.e. the arraylist. We have exposed a method 'getCommand' which takes a
string and gives back the abstract object 'IExecute'. The client code is now neat and clean. All the 'IF' conditions are now
moved to the 'clsInvoker' class.
Figure 27. Invoker and the clean client

Abstract Class vs Interface - Real time scenarios to decide when to use abstract class and
when to use interface.
The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. In this article I
will describe what is the main difference between interface and abstract class? And what could be the real time scenarios to use
abstract class and interface?

Abstract Class

Abstract class is a special type of class which cannot be instantiated and acts as a base class for other classes. Commonly, you
would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can
make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class can contain either abstract methods or non-abstract methods. Abstract members do not have any
implementation in the abstract class, but the same has to be provided in its derived class.

An abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non-
abstract members.
abstract class absClass
{
public abstract void abstractMethod();

public void NonAbstractMethod()


{
Console.WriteLine("NonAbstract Method");
}
}
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.

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

An interface defines a contract. An interface is not a class; it is an entity that is defined by the word Interface. The interface itself
does not provide implementations for the members that it defines. An interface declaration may declare zero or more members.
The members of an interface must be methods, properties, events, or indexers.
interface IInterface
{
public void Method1();

public void Method2();


}

The main difference between them is that a class can implement more than one interface but can only inherit from one abstract
class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Difference between Abstract Class & Interface

1. Multiple Inheritances
o A class can inherit several interfaces.
o A class can inherit only one abstract class.
2. Default implementation
o An interface just defines a contract, it cannot provide any implementation.
o An abstract class can provide complete, default code and/or just the details that have to be overridden.
3. Access Modifiers
o An interface cannot have access modifiers for its members; all the members of interface are implicitly public.
o An abstract class can contain access modifiers for its members. But abstract members cannot have private access
modifier.
4. Fields and Constants
o Fields and constants cannot be defined in interfaces.
o An abstract class can have fields and constants.
5. Constructor
o An interface cannot have constructor.
o An abstract class can have constructor.
6. Static Members
o Member of an interface cannot be static.
o Only Complete Member of abstract class can be Static.
7. Adding new functionality
o If we need to add a new method to an Interface then we will have to track down all the implementations of the
interface and define implementation for the new method in all child classes.
o If we need to add a new method to an abstract class then we have the option of providing default
implementation of that method in base class and therefore all the existing code might work properly.
8. Core VS Peripheral
o Interfaces are used to define the peripheral abilities of a class.
o An abstract class defines the core identity of a class.
Real time scenarios to decide when to use Abstract Class and when to use Interface

The MSDN states: "By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability
is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if
you want to simulate inheritance for structs, because they can't actually inherit from another struct or class."

Let me describe more scenarios in details here:

1. Homogeneity

If various implementations only share method signatures then it is better to use Interfaces. If various implementations are
of the same kind and use common behavior or status then abstract class is better to use. Abstract classes allow you to
partially implement your class, whereas interfaces contain no implementation for any members.

2. Size of Application

If you are designing small and short functionality then use interfaces. If you are designing large functional units, use an
abstract class.

3. Future Expansion

If there is a chance of future expansion of your functionality/classes then abstract class is a good choice. Abstract classes
provide a simple and easy way to version your components. By updating the base class, all inheriting classes are
automatically updated with the change. Interfaces, on the other hand, should not be changed once created. If a new
version of an interface is required, you must create a whole new interface.

On a different note, if there is any need, it is easy to add a new interface to the hierarchy. However, if you already have an
abstract class in your hierarchy, you can't add another, i.e., you can only add an abstract class if there is not one available.
4. Objects Type

If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract
classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing
common functionality to unrelated classes.

5. Decupling

You can use interfaces to decouple your application's code (Dependency Injection) from any particular implementation of
it.

GarbageCollector

What is garbage collection(GC)?


The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you use the new operator to create an
object, the runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues
to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory.
The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage
collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary
operations to reclaim their memory.

What Object.Finalize method does?


allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object.
What are the limitations of Finalizers?
· The exact time of execution during garbage collection is undefined.

 · The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other.
· The thread on which the finalizer is run is unspecified.
Finalize cannot be called on resurrected objects during garbage collection.

What is strong reference and what is weak reference?


There are two types of memory references, strong & weak. When a root references an object, it is said to be a strong reference as the object is being pointed to
by application code. The other type of object, that is not being referenced by the application code is called the weak reference, and this may be collected by the
GC. However, this may still be accessed by the application code if required. But for the application to access the weakly referenced object, this has to be
converted to a strong reference (and note that this has to be done before the GC collects the weakly referenced object).

What is Dispose Method?


A type's Dispose method should release all the resources that it owns. It should also release all resources owned by its base types by calling its parent type's
Dispose method. The parent type's Dispose method should release all resources that it owns and in turn call its parent type's Dispose method, propagating this
pattern through the hierarchy of base types. To help ensure that resources are always cleaned up appropriately, a Dispose method should be callable multiple
times without throwing an exception.
A Dispose method should call the GC.SuppressFinalize method for the object it is disposing. If the object is currently on the finalization queue,
GC.SuppressFinalize prevents its Finalize method from being called. Remember that executing a Finalize method is costly to performance. If your Dispose
method has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalize method.

What will you do to prevent the garbage collector from calling Object.Finalize on an object that does not require it?
call GC.SuppressFinalize() method .
What are Destructors?

Destructors are the C# mechanism for performing cleanup operations. Destructors are used to destruct instances of classes. A class can only have one
destructor.Destructors cannot be inherited or overloaded. · Destructors cannot be called. They are invoked automatically.

} The destructor implicitly calls Finalize on the base class of the object. Finalize method is called recursively for all instances in the inheritance chain, from the
most-derived to the least-derived. Empty destructors should not be used. When a class contains a destructor, an entry is created in the Finalize queue. When
the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance. The
programmer has no control over when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects
that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used
to store the object. Destructors are also called when the program exits. It is possible to force garbage collection by calling Collect, but most of the time, this
should be avoided because it may create performance issues

Explain About latency modes?

To reclaim objects, the garbage collector must stop all of an application's executing threads. In some situations, such as when an application retrieves data or
displays content, a full garbage collection can occur at a critical time and impede performance. You can adjust the intrusiveness of the garbage collector by
setting the LatencyMode property to one of the GCLatencyMode values.
Latency refers to the time that the garbage collector intrudes in your application. During low latency periods the garbage collector is more conservative, and
less intrusive, in reclaiming objects. Generation 2 collections occur less frequently, which causes the application working set to grow over time. As a result, it is
recommended that you use the LowLatency mode only for the short period of time when it is needed. Otherwise, if the system is under memory pressure, the
garbage collector will trigger a collection, which can briefly pause the application and disrupt a time-critical operation.
You should use the latency mode with applications that include a block of code that runs over a brief period of time and must run with minimal interruptions
from the runtime. Although the LowLatency mode is designed to be used in scenarios where there are some time constraints, it is not intended to be a solution
for scenarios where there are strict real-time constraints.

How many Options of Latencymode for garbage collector? what are they?

There are three latency modes

1)Batch: Disables garbage collection concurrency and reclaims objects in a batch call. This is the most intrusive mode.This mode is designed for maximum
throughput at the expense of responsiveness.

2)Interactive:The default latency mode. Enables garbage collection concurrency and reclaims objects while the application is running.

3)LowLatency:Enables garbage collection that is more conservative in reclaiming objects. Collections occur less frequently. This is the least intrusive mode.
This mode is not available on the server garbage collector.

Other Questions:

1)If i have 100 objects in my application are out of scope.when first time garbage collected how many objects memory reference are
free?

All the objects of genereation 0 are freed.

2)destructor, Dispose, Finalize - How they relate to each other?

These are used to release unmanaged resources


3)How we free the memory in C#.NET.

The .NET Framework's garbage collector manages the allocation and release of memory for your application.

4)How u call destructor and dispose methode in c#.NET

for destructor :

class Car
{
~Car() // destructor
{
// cleanup statements...
}
}

For Dispose:

DisposableResource TestObj = new DisposableResource(fs);

TestObj.Dispose();

5)Where Destructors Can not be defined?

in structs
6)What are the different generaions of Garbage Collection and how do they work ?

Generations in the Garbage Collector is a way of enhancing the garbage collection performance.There are 3 Generations...0,1,2.

Generation 0 - When an object is initialized, its in generation 0. These are new objects that have never been played around with by the GC. As and when more
objects get created, the process of Garbage Collection is invoked by the CLR. Generation 1 - The objects that survive the garbage collection process are
considered to be in generation 1. These are the old objects.Generation 2 - As more new objects get created and added to the memory, the new objects are
added to generation 0, the generation 1 old objects become older, and so are considered to be in generation 2. Generation 2 is the highest level generation in
the garbage collection process. Any further garbage collection process occuring causes the level 1 objects promoted to level 2, and the level 2 objects stay in
level 2 itself, as this generation level is the highest level.

7)Does c# supports destructors?

yes .The destructor implicitly calls Finalize on the base class of the object.

Extension Methods
An extension method is a new language feature of C# starting with the 3.0 specification, as well as Visual Basic.NET starting with 9.0 and Oxygene with 2.0.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in
C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

What are extension methods?

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
How to use extension methods?

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the
type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Benefits of extension methods

 Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
 If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.
 This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.
Extension Methods Usage
This section is optional reading section for understanding the core idea of extension methods:

a. This keyword has to be the first parameter in the extension method parameter list.
b. Extension methods are used extensively in C# 3.0 and further version specially for LINQ extensions in C#, for example:
Collapse | Copy Code

int[] ints = { 10, 45, 15, 39, 21, 26 };

var result = ints.OrderBy(g => g);


Here, order by is a sample for extension method from an instance of IEnumerable<T> interface, the expression inside the parenthesis is a lambda expression.

c. It is important to note that extension methods can't access the private methods in the extended type.
d. If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that
type.
e. If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be
called.

Important points for the use of extension methods


 An extension method must be defined in a top-level static class.
 An extension method with the same name and signature as an instance method will not be called.
 Extension methods cannot be used to override existing methods.
 The concept of extension methods cannot be applied to fields, properties or events.
 Overuse of extension methods is not a good style of programming.

namespace ConsoleApplication11
{
//extension methods must be defined in a static class
static class IntMethods
{
//extension methods must be static
//the this keyword tells C# that this is an extension method
public static bool IsPrime(this int number)
{
//check for evenness
if (number % 2 == 0)
{
if (number == 2)
return true;
return false;
}
//you don’t need to check past the square root
int max = (int)Math.Sqrt(number);
for (int i = 3; i <= max; i += 2)
{
if ((number % i) == 0)
{
return false;
}
}
return true;
}
}
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; ++i)
{
if (i.IsPrime())
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}
}
}

Note:
o The difference between a regular static method and an extension method is the special this keyword for the first argument.
o Extension method cannot be declared on a class or struct.
o It can also be declared on an interface (such as IEnumerable<T>). Normally, an interface wouldn’t have any implementation.
With extension methods, however, you can add methods that will be available on every concrete implementation of the
interface
o Language Integrated Query (LINQ) is one of the best examples of how you can use this technique to enhance existing code.

Index

Q1: What is the difference between a Heap table and a Clustered table? How
can we identify if the table is a heap table?
A Heap table is a table in which, the data rows are not stored in any particular order within each data page. In addition, there is no particular order to
control the data page sequence, that is not linked in a linked list. This is due to the fact that the heap table contains no clustered index.
A clustered table is a table that has a predefined clustered index on one column or multiple columns of the table that defines the storing order of the
rows within the data pages and the order of the pages within the table, based on the clustered index key.
The heap table can be identified by querying the sys.partitions system object that has one row per each partition with index_id value equal to 0. You
can also query the sys.indexes system object also to show the heap table index details, that shows, the id of that index is 0 and the type of it is HEAP.
For more information, see the article: SQL Server table structure overview.

Q2: Explain how the SQL Server Engine uses an Index Allocation Map (IAM)?
SQL Server Engine uses an Index Allocation Map (IAM) to keep an entry for each page to track the allocation of these available pages. The IAM is
considered as the only logical connection between the data pages, that the SQL Server Engine will use to move through the heap.
For more information, see the article: SQL Server table structure overview.

Q3: What is the “Forwarding Pointers issue” and how can we fix it?
When a data modification operation is performed on heap table data pages, Forwarding Pointers will be inserted into the heap to point to the new
location of the moved data. These forwarding pointers will cause performance issues over time due to visiting the old/original location vs the new
location specified by the forwarding pointers to get a specific value.

Starting from SQL Server version 2008, a new method was introduced to overcome the forwarding pointers performance issue, by using the ALTER
TABLE REBUILD command, that will rebuild the heap table.

For more information, see the article: SQL Server table structure overview.

Q4: What is a SQL Server Index?


A SQL Server index is considered as one of the most important factors in the performance tuning process. Indexes are created to speed up the data
retrieval and the query processing operations from a database table or view, by providing swift access to the database table rows, without the need to
scan all the table’s data, in order to retrieve the requested data.

You can imagine a table index akin to a book’s index that allows you to find the requested information very fast within your book, rather than reading
all the book pages in order to find a specific item you are looking for.

For more information, see the article: SQL Server index structure and concepts.

Q5: Describe the structure of a SQL Server Index that provides faster access
to the table’s data?
A SQL Server index is created using the shape of B-Tree structure, that is made up of 8K pages, with each page, in that structure, called an index node.
The B-Tree structure provides the SQL Server Engine with a fast way to move through the table rows based on index key, that decides to navigate left
or right, to retrieve the requested values directly, without scanning all the underlying table rows. You can imagine the potential performance
degradation that may occur due to scanning large database table.

The B-Tree structure of the index consists of three main levels:

 the Root Level, the top node that contains a single index page, form which SQL Server starts its data search,
 the Leaf Level, the bottom level of nodes that contains the data pages we are looking for, with the number of leaf pages depends on the
amount of data stored in the index,
 and finally the Intermediate Level, one or multiple levels between the root and the leaf levels that holds the index key values and pointers to
the next intermediate level pages or the leaf data pages. The number of intermediate levels depends on the amount of data stored in the
index.

For more information, see the article: SQL Server index structure and concepts.
Q6: Explain Index Depth, Density and Selectivity factors and how these
factors affect index performance?
 Index depth is the number of levels from the index root node to the leaf nodes. An index that is quite deep will suffer from performance
degradation problem. In contrast, an index with a large number of nodes in each level can produce a very flat index structure. An index with
only 3 to 4 levels is very common.
 Index density is a measure of the lack of uniqueness of the data in a table. A dense column is one that has a high number of duplicates.
 Index selectivity is a measure of how many rows scanned compared to the total number of rows. An index with high selectivity means a small
number of rows scanned when related to the total number of rows.

For more information, see the article: SQL Server index structure and concepts.

Q7: What is the difference between OLTP and OLAP workloads and how do
they affect index creation decisions?
On Online Transaction Processing (OLTP) databases, workloads are used for transactional systems, in which most of the submitted queries are data
modification queries.
In contrast, Online Analytical Processing (OLAP) database workloads are used for data warehousing systems, in which most of the submitted queries
are data retrieval queries that filter, group, aggregate and join large data sets quickly.

Creating a large number of indexes on a database table affects data modification (e.g. Updates) operation performance. When you add or modify a
row in the underlying table, the row will also be adjusted appropriately in all related table indexes. Because of that, you need to avoid creating a large
number of indexes on the heavily modified tables and create the minimum possible number of indexes, with the least possible number of columns on
each index. For Online Analytical Processing (OLAP) workloads, in which tables have low modification requirements, you can create a large number of
indexes that improve the performance of the data retrieval operations

For more information, see the article: SQL Server index design basics and guidelines.
Q8: Why it is not recommended to create indexes on small tables?
It takes the SQL Server Engine less time scanning the underlying table than traversing the index when searching for specific data. In this case, the index
will not be used but it will still negatively affect the performance of data modification operations, as it will be always adjusted when modifying the
underlying table’s data.

For more information, see the article: SQL Server index design basics and guidelines.

Q9: What are some different ways to create an index?


 CREATE INDEX T-SQL statement.
 Using SQL Server Management Studio, by browsing the table on which you need to create an index, right click on the Indexes node and
choose New Index option.
 Indirectly by defining the PRIMARY KEY and the UNIQUE constraint within the CREATE TABLE or ALTER TABLE statements.

For more information, see the article: SQL Server index operations.

Q10: What are the pros and cons of using ONLINE index creation or
rebuilding options?
Setting the ONLINE option to ON when you create or rebuild the index will enable other data retrieving or modification processes on the underlying
table to continue, preventing the index creation process from locking the table. On the other hand, the ONLINE index creation or rebuilding process
will take longer time than the offline default index creation process.

For more information, see the article: SQL Server index operations.

Q11: What is the difference between PAD_INDEX and FILLFACTOR?


 FILLFACTOR isused to set the percentage of free space that the SQL Server Engine will leave in the leaf level of each index page during index
creation. The FillFactor should be an integer value from 0 to 100, with 0 or 100 is the default value, in which the pages will be filled completely
during the index creation.
 PAD_INDEX is used to apply the free space percentage specified by FillFactor to the index intermediate level pages during index creation.

For more information, see the article: SQL Server index operations.

Q12: How many Clustered indexes can be created on a table and why?
SQL Server allows us to create only one Clustered index per each table, as the data can be sorted in the table using only one order criteria.
For more information, see the article: Designing effective SQL Server clustered indexes.

Q13: Describe the characteristics ideal Clustered index keys.


 Short: Although SQL Server allows us to add up to 16 columns to the clustered index key, with a maximum key size of 900 bytes, the typical
clustered index key is much smaller than what is allowed, with as few columns as possible. A wide Clustered index key will also affect all non-
clustered indexes built over that clustered index, as the clustered index key will be used as a lookup key for all the non-clustered indexes
pointing to it.
 Static: It is recommended to choose columns that are not changed frequently in a clustered index key. Changing the clustered index key values
means that the whole row will be moved to the new proper page to keep the data values in the correct order.
 Increasing: Using an increasing (aka incrementing) column, such as the IDENTITY column, as a clustered index key will help in improving the
INSERT process, that will directly insert the new values at the logical end of the table. This highly recommended choice will help in reducing the
amount of memory required for the page buffers, minimize the need to split the page into two pages to fit the newly inserted values and the
fragmentation occurrence, that required rebuilding or reorganizing the index again.
 Unique: It is recommended to declare the clustered index key column or combination of columns as unique to improve query performance.
Otherwise, SQL Server will automatically add a uniqueifier column to enforce the clustered index key uniqueness.
 Accessed frequently: This is due to the fact that the rows will be stored in the clustered index in a sorted order based on that index key that is
used to access the data.
 Used in the ORDER BY clause: In this case, there no need for the SQL Server Engine to sort the data in order to display it, as the rows are
already sorted based on the index key used in the ORDER BY clause.
For more information, see the article: Designing effective SQL Server clustered indexes.

Q14: Why it is not recommended to use GUID and CHARACTER columns as


Clustered index keys?
For GUID columns, that are stored in UNIQUE IDENTIFIER columns, the main challenge that affects the clustered index key sorting performance is the
nature of the GUID value that is larger than the integer data types, with 16 bytes size, and that it is generated in random manner, different from the
IDENTITY integer values that are increasing continuously.

For the CHARACTER columns. The main challenges include limited sorting performance of the character data types, the large size, non-increasing
values, non-static values that often tend to change in the business applications and not compared as binary values during the sorting process, as the
characters comparison mechanism depends on the used collation.

For more information, see the article: Designing effective SQL Server clustered indexes.

Q15: What is the main difference between a Clustered and Non-Clustered


index structure?
A Non-clustered index is different from a Clustered index in that, the underlying table rows will not be stored and sorted based on the Non-clustered
key, and the leaf level nodes of the Non-clustered index are made of index pages instead of data pages. The index pages of the Non-clustered index
contain Non-clustered index key values with pointers to the storage location of these rows in the underlying heap table or the Clustered index.

For more information, see the article: Designing effective SQL Server non-clustered indexes.
Q16: What is the main difference between a Non-clustered index that is built
over a Heap table and a Non-clustered index that is built over a Clustered
table? What is the difference between a RID Lookup and a Key Lookup?
If a Non-Clustered index is built over a Heap table or view (read more about SQL Server indexed views, that have no Clustered indexes) the leaf level
nodes of that index hold the index key values and Row ID (RID) pointers to the location of the rows in the heap table. The RID consists of the file
identifier, the data page number, and the number of rows on that data page.
On the other hand, if a Non-clustered index is created over a Clustered table, the leaf level nodes of that index contain Non-clustered index key
values and clustering keys for the base table, that are the locations of the rows in the Clustered index data pages.
A RID Lookup operation is performed to retrieve the rest of columns that are not available in the index from the heap table based on the ID of each
row.
A Key Lookup operation is performed to retrieve the rest of columns that are not available in the index from the Clustered index, based on the
Clustered key of each row,
For more information, see the article: Designing effective SQL Server non-clustered indexes.

Q17: How could we benefit from the INCLUDE feature to overcome Non-
Clustered index limitations?
Rather than creating a Non-clustered index with a wide key, large columns that are used to cover the query can be included to the Non-clustered
index as non-key columns, up to 1023 non-key columns, using the INCLUDE clause of the CREATE INDEX T-SQL statement, that was introduced in
SQL Server 2005, with a minimum of one key column.
The INCLUDE feature extends the functionality of Non-clustered indexes, by allowing us to cover more queries by adding the columns as non-key
columns to be stored and sorted only in the leaf level of the index, without considering that columns values in the root and intermediate levels of the
Non-clustered index. In this case, the SQL Server Query Optimizer will locate all required columns from that index, without the need for any extra
lookups. Using the included columns can help to avoid exceeding the Non-clustered size limit of 900 bytes and 16 columns in the index key, as the
SQL Server Database Engine will not consider the columns in the Non-clustered index non-key when calculating the size and number of columns of
the index key. In addition, SQL Server allows us to include the columns with data types that are not allowed in the index key, such as VARCHAR(MAX),
NVARCHAR(MAX), text, ntext and image, as Non-clustered index non-key columns.
For more information, review SQL Server non-clustered indexes with included columns.

Q18: Which type of indexes are used to maintain the data integrity of the
columns on which it is created?
Unique Indexes, by ensuring that there are no duplicate values in the index key, and the table rows, on which that index is created.
For more information, see the article: Working with different SQL Server indexes types.

Q19: How could we benefits from a Filtered index in improving the


performance of queries?
It uses a filter predicate to improve the performance of queries that retrieve a well-defined subset of rows from the table, by indexing the only portion
of the table rows. The smaller size of the Filtered index, that consumes a small amount of the disk space compared with the full-table index size, and
the more accurate filtered statistics, that cover the filtered index rows with only minimal maintenance cost, help in improving the performance of the
queries by generating a more optimal execution plan.

For more information, see the article: Working with different SQL Server indexes types.

Q20: What are the different ways that can be used to retrieve the properties
of the columns participating in a SQL Server index?
 Using SSMS, by expanding the Indexes node under a database tabl, then right-clicking on each index, and choose the Properties option. The
problem with gathering the indexes information using the UI method is that you need to browse it one index at a time per each table. You can
imagine the effort required to see the article: all indexes in a specific database.
 The sp_helpindex system stored procedure, by providing the name of the table that you need to list its indexes. In order to gather
information about all indexes in a specific database, you need to execute the sp_helpindex number of time equal to the number of tables in
your database.
 The sys.indexes system dynamic management view. The sys.indexes contains one row per each index in the table or view. It is recommended
to join sys.indexes DMV with other systems DMVs, such as the sys.index_columns, sys.columns and sys.tables in order to return meaningful
information about these indexes.

For more information, see the article: Gathering SQL Server indexes statistics and usage information.

Q21: How can we get the fragmentation percentage of a database index?


 Using SSMS, from the Fragmentation tab of the index Properties window. Checking the fragmentation percentage of all indexes in a specific
database, using the UI method requires a big effort, as you need to check one index at a time.
 The sys.dm_db_index_physical_stats dynamic management function, that was first Introduced in SQL Server 2005. The
sys.dm_db_index_physical_stats DMF can be joined with the sys.indexes DMV to return the fragmentation percentage of all indexes under the
specified database.

For more information, see the article: Gathering SQL Server indexes statistics and usage information.

Q22: When checking the index usage statistics information, retrieved by


querying the sys.dm_db_index_usage_stats dynamic management view,
explain the results of the returned number of seeks, scans, lookups and
updates.
 The number of Seeks indicates the number of times the index is used to find a specific row,
 the number of Scans shows the number of times the leaf pages of the index are scanned,
 the number of Lookups indicates the number of times a Clustered index is used by the Non-clustered index to fetch the full row
 and the number of Updates shows the number of times the index data has modified.

For more information, see the article: Gathering SQL Server indexes statistics and usage information.

Q23: What is the difference between index Rebuild and Index Reorganize
operations?
Index fragmentation can be resolved by rebuilding and reorganizing SQL Server indexes regularly. The Index Rebuild operation removes
fragmentation by dropping the index and creating it again, defragmenting all index levels, compacting the index pages using the Fill Factor values
specified in rebuild command, or using the existing value if not specified and updating the index statistics using FULLSCAN of all the data.
The Index Reorganize operation physically reorders leaf level pages of the index to match the logical order of the leaf nodes. The index reorganizes
operation will be always performed online. Microsoft recommends fixing index fragmentation issues by rebuilding the index if the fragmentation
percentage of the index exceeds 30%, where it recommends fixing the index fragmentation issue by reorganizing the index if the index fragmentation
percentage exceeds 5% and less than 30%.
For more information, see the article: Maintaining SQL Server indexes.

Q24: How can you find the missing indexes that are needed to potentially
improve the performance of your queries?
 The Missing Index Details option in the query execution plan, if available.
 The sys.dm_db_missing_index_details dynamic management view, that returns detailed information about missing indexes, excluding spatial
indexes,
 A combination of the SQL Server Profiler and the Database Engine Tuning Advisor tools.

For more information, see the article: Tracing and tuning queries using SQL Server indexes.

Q25: Why is an index described as a double-edged sword?


A well-designed index will enhance the performance of your system and speed up the data retrieval process. On the other hand, a badly-designed
index will cause performance degradation on your system and will cost you extra disk space and delay in the data insertion and modification
operations. It is better always to test the performance of the system before and after adding the index to the development environment, before adding
it to the production environment.

Stored Procedure

Below are the list of Best Stored procedures Interview questions and Answers

1) What do you understand by a stored procedure?

The group of SQL statements which are or have been stored in the server database is known as a stored procedure. Input parameters are accepted in the
stored procedures so that several clients can use that single procedure over the network using that single input data. It holds an advantage that whenever the
procedure gets updated; all the clients automatically get the updated version. Stored procedures help in reducing the network traffic and also improve the
performance of the data. The integrity of data can be ensured while making use of stored procedures.

2) Mention the uses of stored procedures.

Stored procedures are used for various different things. Some of the uses of stored procedures are as follows:

 Stored procedures are often used as access control mechanism and for data validation.
 The logic applied in this application is centralized and is stored in the application.
 Procedures are used to process the huge amount of data for complex procedures and functionalities and for logic implementation access of their data.
 These procedures are used to store data in them and can be accessed by procedures.
 They support modular programming.
 Faster execution takes place.
 It can also be used as a security mechanism.
 They are used for reducing network traffic.
3) What are the types of stored procedures in an SQL server?
The types of stored procedures present in an SQL server are listed as follows: –

 User-defined stored procedures– these are the modules or routines which encapsulate code for reuse. There are 2 types of user-defined stored
procedures:
 Transact-SQL: It is a collection of transaction SQL statements which takes and returns user-specified parameters.
 CLR: It is a reference to the Microsoft .NET framework.
 Extended stored procedures– with the help of these procedures, you can create your own external routine in a programming language.
 System stored procedures– these are used to perform various administrative activities in the SQL server.

4) What are the advantages of using a stored procedure?

The following are the advantages of using a stored procedure: –

 It reduces the network usage between the client and the server and an immediate processing is performed on the database server. It hence reduces the
unnecessary data transfer.
 Security is improved and the user access to the stored procedure is managed by the administrator.
 Development cost reduces and reliability increases.
 It improves the performance of the database.
 These are used to encapsulate the logic and hence the code can be changed without affecting the clients.
 The access to other database objects becomes more secure.
 SQL injection attacks can be avoided using this.

5) What are the disadvantages of using the stored procedures?

Everything which has advantages has disadvantages too. The disadvantages of using stored procedures are listed below:

 Specialized skills are required for writing and maintaining the code of a stored procedure.
 Debuggers are not available for a stored procedure.
 The language in which a stored procedure is written may differ from one database to the other.
 Exception handling in a stored procedure is not up to the mark.
 These are tightly coupled to the database.
 You may not be able to use objects.
 Sometimes the logic may not be understood by the programmers.

6) How will you optimize a stored procedure optimization?

The various tips and tricks for optimising a stored procedure optimization are listed below:

1. “SET NOCOUNT ON” statement should be included.


2. A schema with its object name should be used.
3. The prefix name “sp_” should not be used in a stored procedure name.
4. Instead of using (SELECT*), use IF EXISTS (SELECT 1).
5. SQL server cursors should be avoided whenever possible.
6. The transaction should be kept as short as possible.
7. In case of error handling, make use of the try-catch block.

7) What are the differences between stored procedure and view in SQL server?
The differences between stored procedure and view in SQL server are as follows:

 A stored procedure accepts parameters. Whereas, views do not accept parameters.


 In any large query, a stored procedure cannot be used as a building block. Whereas, a view can be used as a building block.
 A stored procedure can contain several statements. Whereas, a view can contain only one single select query.
 Using stored procedures, one or more tables can be modified. Whereas, using view no table can be modified.
 A view can be used within a stored procedure. Whereas, a stored procedure cannot be used inside a view.

8) List some major differences between triggers and stored procedures?


Following are some differences between stored procedures and triggers:
 Event and actions needs to be identified at the time of creating a trigger. Whereas, at the time of creating a stored procedure, it is not important.
 Trigger can be run automatically when any event occurs. Whereas, stored procedures have to be run manually.
 A stored procedure can be called within a trigger. Whereas, a trigger cannot be called in a stored procedure.
 Triggers execute implicitly. Whereas, stored procedures execute explicitly.
 A trigger cannot be called from front end. Whereas, a stored procedure can be.

9) What do you understand by recursive stored procedures?

Repetitive tasks are being performed by the recursive stored procedures. By default this function is disabled but can be activated using a
particular command. The command is as follows-

Max_sp_recursion_depth;
After using this, the system variable should be renamed to a non-zero variable.

10) When would you use the stored procedures or functions?

As we all know, functions are the computed values and they cannot perform any permanent environmental changes to the SQL server. Neither insertion in the
statement is allowed nor can it be updated. If a function returns a scalar value or can be joined upon if it returns a scalar set, then it can be used inline in the
SQL statements. These are used when the logic applied in the application is centralized and the data is stored in the application. These stored procedures are
used when we need to validate the data and the complex procedures.

https://www.monsterindia.com/career-advice/top-8-c-interview-questions-and-answers-for-experience-professionals-
7859.html

Usually C# interview questions for experienced professionals are specifically structured to elicit more targeted responses and
garner better insights. This is done with the intent of determining whether you are the best fit for the job on offer.
Here’s a list of 8 important C# questions that you should go through before your next interview.

1. How would you implement the Singleton design pattern in C#?

There are numerous ways to implement Singleton in C#:

• Standard Singleton Implementation


• Early Instance Creation
• Double Checked Locking
• Using Generics
• Fully Lazy Instantiation
• Using Lazy type

2. Describe the Async method of C#?

Async (asynchronous programming) can be described as a method that returns to the calling method before finishing its
work fully. It then proceeds to complete its work while the calling method goes along with its execution.

3. What is an Object?

An object is an instance of a class and comprises of real values as opposed to variables. For instance, say we were to create
an instance of the class Employee called “Raj”.
Employee Raj = new Employee();
We will now be able to access all the methods in the class “Employee” via object “Raj” as given below.
Raj.setName(“XYZ”);

4. Is it possible to serialise hashtables?

It is not possible to serialise hashtables – a collection of key-value pairs – as the .NET Framework prevents serialisation of
any object that implements the IDictionary interface. The XmlSerializer class will display an error when an attempt is made
to serialise a Hashtable.
5. Explain the differences between “out” and “ref” parameters in C#?

Although quite similar, the "out" parameter can be passed to a method and doesn't require to be initialised whereas the "ref"
parameter has to be initialised and set to something before it is used.

6. Can you explain the concept of inner exception in C#?

An inner exception can be described as a property of exception class which gives you a brief understanding of the exception,
i.e., details on the parent exception as well as the child exception.

You may also like: How do you Create a Plan B for your Career

7. Explain the use of the System. Environment class in C#.NET.

The System. Environment class provides all relevant information about the current environment and platform. It can also be
used to retrieve information such as:

a. Command-line arguments
b. The exit code
c. Environment variable settings
d. Contents of the call stack
e. Time since last system boot
f. The version of the common language runtime

Further, if you’re looking to retrieve environment variable settings, version of the common language runtime, etc., the
System, environment class can help you do so.

8. Explain what is Namespaces in C#.

In C#, Namespaces are usually used to organise and provide a level of separation of codes. Indicated by the keyword
“namespace,” they can also be put to use to compose substantial code ventures.
• Can you explain the difference between the “throw” and “throw ex” in .NET?
• How does C# handle encapsulation?
• Explain the use of GetCommandLineArgs() method in C#.NET?
• What is Abstract Class in C#?
• Describe the use of Virtual Keyword in C#?
• How to create a custom exception in C# .net program? Describe its use.
• Describe method hiding in C# inheritance? Explain its uses with an example.
• What would you choose between the C# interface and abstract class?
• Can you shed light on what delegates are in C# Programming?
• Why is the singleton pattern considered to be an anti-pattern?
• Elaborate on the differences between shadow and override?

Last but not the least, do note that once your interview is over, you should ideally have a list of questions for your
interviewer. This not only helps you find out more about the job you're applying for but also helps your potential employer
justify their decision of calling you in for the interview.

All the best!

https://www.guru99.com/c-sharp-interview-questions.html

Here are some frequently asked interview questions for freshers as well as experienced C# developers candidates to get the
right job.

1. What is C#?

C# is an object-oriented, type-safe, and managed language that is compiled by .Net framework to generate Microsoft
Intermediate Language.

2. Explain types of comment in C# with examples


Single line

Example:

//This is a single line comment

ii. Multiple line (/* */)

Example:

/*This is a multiple line comment


We are in line 2
Last line of comment*/

iii. XML Comments (///).

Eg:

/// summary;
/// Set error message for multilingual language.
/// summary

3. Can multiple catch blocks be executed?

No, Multiple catch blocks can't be executed. Once the proper catch code executed, the control is transferred to the finally
block, and then the code that follows the finally block gets executed.

4. What is the difference between public, static, and void?


Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are
globally accessible without creating an instance of the class. Static member are by default not globally accessible it depends
upon the type of access modified used. The compiler stores the address of the method as the entry point and uses this
information to begin execution before any objects are created. And Void is a type modifier that states that the method or
variable does not return any value.

5. What is an object?

An object is an instance of a class through which we access the methods of that class. "New" keyword is used to create an
object. A class that creates an object in memory will contain the information about the methods, variables, and behavior of
that class.

6. Define Constructors

A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked
whenever an object class is created. It constructs the values of data members while initializing the class.

7. What is Jagged Arrays?

The Array which has elements of type array is called jagged Array. The elements can be of different dimensions and sizes. We
can also call jagged Array as an Array of arrays.

8. What is the difference between ref & out parameters?

An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be
initialized before passing to a method.

9. What is the use of 'using' statement in C#?


The 'using' block is used to obtain a resource and process it and then automatically dispose of when the execution of the
block completed.

10. What is serialization?

When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The
process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should
implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

11. Can we use "this" command within a static method?

We can't use 'This' in a static method because we can only use static variables/methods in a static method.

12. What is the difference between constants and read-only?

Constant variables are declared and initialized at compile time. The value can't be changed afterward. Read-only is used
only when we want to assign the value at run time.

13. What is an interface class? Give one example of it

An Interface is an abstract class which has only public abstract methods, and the methods only have the declaration and not
the definition. These abstract methods must be implemented in the inherited classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
interface Guru99Interface
{
void SetTutorial(int pID, string pName);
String GetTutorial();
}

class Guru99Tutorial : Guru99Interface


{
protected int TutorialID;
protected string TutorialName;

public void SetTutorial(int pID, string pName)


{
TutorialID = pID;
TutorialName = pName;
}

public String GetTutorial()


{
return TutorialName;
}

static void Main(string[] args)


{
Guru99Tutorial pTutor = new Guru99Tutorial();

pTutor.SetTutorial(1,".Net by Guru99");
Console.WriteLine(pTutor.GetTutorial());

Console.ReadKey();
}
}
}

14. What are value types and reference types?

A value type holds a data value within its own memory space. Example

int a = 30;

Reference type stores the address of the Object where the value is being stored. It is a pointer to another memory location.

string b = "Hello Guru99!!";

15. What are Custom Control and User Control?

Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can be added to toolbox.
Developers can drag and drop controls to their web forms. Attributes can, at design time. We can easily add custom controls
to Multiple Applications (If Shared Dlls). So, If they are private, then we can copy to dll to bin directory of web application
and then add reference and can use them.

User Controls are very much similar to ASP include files, and are easy to create. User controls can't be placed in the toolbox
and dragged - dropped from it. They have their design and code-behind. The file extension for user controls is ascx.

16. What are sealed classes in C#?


We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from
a class. If we forcefully specify a sealed class as base class, then a compile-time error occurs.

17. What is method overloading?

Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we
compile, the compiler uses overload resolution to determine the specific method to be invoke.

18. What is the difference between Array and Arraylist?

In an array, we can have items of the same type only. The size of the array is fixed when compared. To an arraylist is similar
to an array, but it doesn't have a fixed size.

19. Can a private virtual method can be overridden?

No, because they are not accessible outside the class.

20. Describe the accessibility modifier "protected internal".

Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived
from this parent class.

21. What are the differences between System.String and System.Text.StringBuilder classes?

System.String is immutable. When we modify the value of a string variable, then a new memory is allocated to the new value
and the previous memory allocation released. System.StringBuilder was designed to have a concept of a mutable string
where a variety of operations can be performed without allocation separate memory location for the modified string.
22. What's the difference between the System.Array.CopyTo() and System.Array.Clone() ?

Using Clone() method, we creates a new array object containing all the elements in the original Array and using CopyTo()
method. All the elements of existing array copies into another existing array. Both methods perform a shallow copy.

23. How can we sort the elements of the Array in descending order?

Using Sort() methods followed by Reverse() method.

24. Write down the C# syntax to catch an exception

To catch an exception, we use try-catch blocks. Catch block can have a parameter of system.Exception type.

Eg:

try {
GetAllData();
}
catch (Exception ex) {
}

In the above example, we can omit the parameter from catch statement.

25. What's the difference between an interface and abstract class?

Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete
methods. In an interface class, all the methods are public. An abstract class may have private methods.

26. What is the difference between Finalize() and Dispose() methods?


Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand, Finalize()
is used for the same purpose, but it doesn't assure the garbage collection of an object.

27. What are circular references?

Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition
and make the resources unusable.

28. What are generics in C#.NET?

Generics are used to make reusable code classes to decrease the code redundancy, increase type safety, and performance.
Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace
should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of
parameterized types.

29. What is an object pool in .NET?

An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of
objects in the pool. This reduces the overhead of creating and re-creating objects.

30. List down the commonly used types of exceptions in .net

ArgumentException, ArgumentNullException , ArgumentOutOfRangeException, ArithmeticException,


DivideByZeroException ,OverflowException ,
IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException , IOEndOfStreamException ,
NullReferenceException , OutOfMemoryException , StackOverflowException etc.

31. What are Custom Exceptions?


Sometimes there are some errors that need to be handled as per user requirements. Custom exceptions are used for them
and are used defined exceptions.

32. What are delegates?

Delegates are same are function pointers in C++, but the only difference is that they are type safe, unlike function pointers.
Delegates are required because they can be used to write much more generic type-safe functions.

33. How do you inherit a class into other class in C#?

Colon is used as inheritance operator in C#. Just place a colon and then the class name.

public class DerivedClass : BaseClass

34. What is the base class in .net from which all the classes are derived from?

System.Object

35. What is the difference between method overriding and method overloading?

In method overriding, we change the method definition in the derived class that changes the method behavior. Method
overloading is creating a method with the same name within the same class having different signatures.

36. What are the different ways a method can be overloaded?

Methods can be overloaded using different data types for a parameter, different order of parameters, and different number
of parameters.
37. Why can't you specify the accessibility modifier for methods inside the interface?

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in
the derived class. That's why they all are public.

38. How can we set the class to be inherited, but prevent the method from being over-ridden?

Declare the class as public and make the method sealed to prevent it from being overridden.

39. What happens if the inherited interfaces have conflicting method names?

Implement is up to you as the method is inside your own class. There might be a problem when the methods from different
interfaces expect different data, but as far as compiler cares you're okay.

40. What is the difference between a Struct and a Class?

Structs are value-type variables, and classes are reference types. Structs stored on the Stack causes additional overhead but
faster retrieval. Structs cannot be inherited.

41. How to use nullable types in .Net?

Value types can take either their normal values or a null value. Such types are called nullable types.

Int? someID = null;


If(someID.HasVAlue)
{
}

42. How we can create an array with non-default values?


We can create an array with non-default values using Enumerable.Repeat.

43. What is difference between "is" and "as" operators in c#?

"is" operator is used to check the compatibility of an object with a given type, and it returns the result as Boolean.

"as" operator is used for casting of an object to a type or a class.

44. What's a multicast delegate?

A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is assigned to a method.

45. What are indexers in C# .NET?

Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as an array.

Eg:

public int this[int index] // Indexer declaration

46. What is difference between the "throw" and "throw ex" in .NET?

"Throw" statement preserves original error stack whereas "throw ex" have the stack trace from their throw point. It is
always advised to use "throw" because it provides more accurate error information.

47. What are C# attributes and its significance?

C# provides developers a way to define declarative tags on certain entities, eg. Class, method, etc. are called attributes. The
attribute's information can be retrieved at runtime using Reflection.
48. How to implement a singleton design pattern in C#?

In a singleton pattern, a class can only have one instance and provides an access point to it globally.

Eg:

Public sealed class Singleton


{
Private static readonly Singleton _instance = new Singleton();
}

49. What is the difference between directcast and ctype?

DirectCast is used to convert the type of object that requires the run-time type to be the same as the specified type in
DirectCast.

Ctype is used for conversion where the conversion is defined between the expression and the type.

50. Is C# code is managed or unmanaged code?

C# is managed code because Common language runtime can compile C# code to Intermediate language.

51. What is Console application?

A console application is an application that can be run in the command prompt in Windows. For any beginner on .Net,
building a console application is ideally the first step, to begin with.

52. Give an example of removing an element from the queue


The dequeue method is used to remove an element from the queue.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Queue qt = new Queue();
qt.Enqueue(1);
qt.Enqueue(2);
qt.Enqueue(3);

foreach (Object obj in qt)


{
Console.WriteLine(obj);
}
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("The number of elements in the Queue " + qt.Count);
Console.WriteLine("Does the Queue contain " + qt.Contains(3));
Console.ReadKey();
}
}
}

https://www.fullstack.cafe/blog/c-sharp-interview-questions

Q1: What is C#? What is C#?

C# 112

Entry

Answer

C# is the programming language for writing Microsoft .NET applications. C# provides the rapid application development found in Visual Basic with the power of C+
+. Its syntax is similar to C++ syntax and meets 100% of the requirements of OOPs like the following:

 Abstraction
 Encapsulation
 Polymorphism
 Inheritance

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

Q2: What is the difference between "continue" and "break" statements in C#? What is the difference between "continue" and "break" statements in C#?

C# 112

Entry

Answer

 using break statement, you can jump out of a loop


 using continue statement, you can jump over one iteration and then resume your loop execution
Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

Q3: What is Managed or Unmanaged Code? What is Managed or Unmanaged Code?

C# 112

Junior

Answer

 Managed Code - The code, which is developed in .NET framework is known as managed code. This code is directly executed by CLR with the help of
managed code execution. Any language that is written in .NET Framework is managed code.
 Unmanaged Code - The code, which is developed outside .NET framework is known as unmanaged code. Applications that do not run under the control of
the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level
functions of the operating system. Background compatibility with the code of VB, ASP and COM are examples of unmanaged code.

Interview Coming Up? Check 112 C# Interview Questions


linkc-sharpcorner.com

HTML5 55

Vue.js 41

Webpack 32

Behavioral 112
Reactive Programming 27

ADO.NET 33

MSMQ 16

Bootstrap 38

MongoDB 82

XML & XSLT 41

Ionic 29

PWA 22

Software Testing 26

Java 147

Python 96

Q4: What is Boxing and Unboxing? What is Boxing and Unboxing?

C# 112

Junior
Answer

Boxing and Unboxing both are used for type conversion but have some difference:

 Boxing - Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When
the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area
in application domain.

 Unboxing - Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done
implicitly, but unboxing have to be explicit by code.

The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of any type can be treated as an object.

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

See All 112 C# Q&A

Q5: What is the difference between a struct and a class in C#? What is the difference between a struct and a class in C#?

C# 112

Junior

Answer

Class and struct both are the user defined data type but have some major difference:

Struct

 The struct is value type in C# and it inherits from System.Value Type.


 Struct is usually used for smaller amounts of data.
 Struct can't be inherited to other type.
 A structure can't be abstract.
 No need to create object by new keyword.
 Do not have permission to create any default constructor.

Class

 The class is reference type in C# and it inherits from the System.Object Type.
 Classes are usually used for large amounts of data.
 Classes can be inherited to other class.
 A class can be abstract type.
 We can't use an object of a class with using new keyword.
 We can create a default constructor.

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

WebSockets 24

Vue.js 41
LINQ 35

Spring 87

TypeScript 39

Java 147

MongoDB 82

T-SQL 36

Redis 25

Golang 49
Ruby on Rails 72

MSMQ 16

Ruby 84

Redux 30

XML & XSLT 41

Q6: Define Property in C#? Define Property in C#?

C# 112

Junior

Answer

Properties are members that provide a flexible mechanism to read, write or compute the values of private fields, in other words by the property we can access private
fields. In other words we can say that a property is a return type function/method with one parameter or without a parameter. These are always public data members.
It uses methods to access and assign values to private fields called accessors.

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com
30+ Docker Interview Questions (ANSWERED) in 2019

#DevOps

#Docker

Q7: Why can't you specify the accessibility modifier for methods inside the interface? Why can't you specify the accessibility modifier for methods inside the interface?

C# 112

Junior

Answer

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are
public.

Interview Coming Up? Check 112 C# Interview Questions

linkguru99.com

See All 112 C# Q&A

Android 113

ASP.NET MVC 33
WCF 33

Bootstrap 38

Ruby 84

Redis 25

Ruby on Rails 72

React 164

ASP.NET 60

CSS 50
ADO.NET 33

AWS 44

Vue.js 41

Q8: How is Exception Handling implemented in C#? How is Exception Handling implemented in C#?

C# 112

Junior

Answer

Exception handling is done using four keywords in C#:

 try – Contains a block of code for which an exception will be checked.


 catch – It is a program that catches an exception with the help of exception handler.
 finally – It is a block of code written to execute regardless whether an exception is caught or not.
 Throw – Throws an exception when a problem occurs.
Interview Coming Up? Check 112 C# Interview Questions

linksoftwaretestinghelp.com

Q9: Can you return multiple values from a function in C#? Can you return multiple values from a function in C#?

C# 112

Junior

Answer

Yes! Using output parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two
values from a function.

Interview Coming Up? Check 112 C# Interview Questions

linktutorialspoint.com

OOP 53
Redis 25

jQuery 51

ADO.NET 33

React 164

AngularJS 62

GraphQL 24

JSON 15
HTML5 55

NoSQL 14

Webpack 32

AWS 44

Q10: What is namespace in C#? What is namespace in C#?

C# 112

Junior

Answer

A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the
same class names declared in another.
Interview Coming Up? Check 112 C# Interview Questions

linktutorialspoint.com

See All 112 C# Q&A

Q11: What are dynamic type variables in C#? What are dynamic type variables in C#?

C# 112

Junior

Answer

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.

Interview Coming Up? Check 112 C# Interview Questions

linktutorialspoint.com

15+ Web Security Interview Questions for Front End Developers (SOLVED)

#Web Security
Behavioral 112

CSS 50

T-SQL 36

Ionic 29

LINQ 35

Code Problems 26

ASP.NET Web API 33

Agile & Scrum 52

Android 113

ASP.NET 60

Python 96

Flutter 68
Reactive Programming 27

PHP 82

Q12: Why to use “finally” block in C#? Why to use “finally” block in C#?

C# 112

Junior

Answer

Finally block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and
at last finally block will be executed. So closing connection to database / releasing the file handlers can be kept in finally block.

Interview Coming Up? Check 112 C# Interview Questions

linka4academics.com

Q13: What is the difference between Interface and Abstract Class? What is the difference between Interface and Abstract Class?

C# 112

Mid

Answer

There are some differences between Abstract Class and Interface which are listed below:

 A class can implement any number of interfaces but a subclass can at most use only one abstract class.
 An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract.
 An abstract class can declare or use any variables while an interface is not allowed to do so.
 In an abstract class all data member or functions are private by default while in interface all are public, we can't change them manually.
 In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don't need to use that.
 An abstract class can't be used for multiple inheritance while interface can be used as multiple inheritance.
 An abstract class use constructor while in an interface we don't have any type of constructor.

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

See All 112 C# Q&A

Vue.js 41

PHP 82

Code Problems 26

Laravel 41

WPF 46

Agile & Scrum 52

Xamarin 83

OOP 53

ADO.NET 33

React Native 72
MongoDB 82

Webpack 32

LINQ 35

Q14: What is the difference between ref and out keywords? What is the difference between ref and out keywords?

C# 112

Mid

Answer

 The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized
before being passed
 The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the
method is reflected in the underlying argument variable in the calling method.

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

Q15: What is delegates in C# and uses of delegates? What is delegates in C# and uses of delegates?

C# 112

Mid

Answer
C# delegates are same as pointers to functions, in C or C++. A delegate Object is a reference type variable that use to holds the reference to a method. The reference
can be changed at runtime which is hold by an object of delegate, a delegate object can hold many functions reference which is also known as Invocation List that
refers functions in a sequence FIFO, we can new functions ref in this list at run time by += operator and can remove by -= operator.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

Data Structures 30

Golang 49

WebSockets 24

CSS 50
Software Testing 26

Ionic 29

AngularJS 62

Spring 87

WPF 46

Agile & Scrum 52

SOA & REST API 66

React Native 72

Docker 55

Q16: What is the difference between overloading and overriding? What is the difference between overloading and overriding?

C# 112

Mid

Answer

 Overloading is when you have multiple methods in the same scope, with the same name but different signatures.

//Overloading
public class test
{
public void getStuff(int id)
{}
public void getStuff(string name)
{}
}

 Overriding is a principle that allows you to change the functionality of a method in a child class.

//Overriding
public class test
{
public virtual void getStuff(int id)
{
//Get stuff default location
}
}

public class test2 : test


{
public override void getStuff(int id)
{
//base.getStuff(id);
//or - Get stuff new location
}
}

Interview Coming Up? Check 112 C# Interview Questions

linkstackoverflow.com

See All 112 C# Q&A

15 ASP.NET Web API Interview Questions And Answers (2019 Update)

#ASP.NET Web API

Q17: Explain Anonymous type in C# Explain Anonymous type in C#

C# 112

Mid

Answer

Anonymous types allow us to create a new type without defining them. This is way to defining read only properties into a single object without having to define type
explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.

Consider:
var anonymousData = new
{
ForeName = "Jignesh",
SurName = "Trivedi"
};

Console.WriteLine("First Name : " + anonymousData.ForeName);

Interview Coming Up? Check 112 C# Interview Questions

linkc-sharpcorner.com

ASP.NET MVC 33

AngularJS 62

Code Problems 26

HTML5 55

Node.js 95

Design Patterns 45

Docker 55

ADO.NET 33
Golang 49

Reactive Programming 27

Laravel 41

GraphQL 24

Entity Framework 57

Q18: What is difference between constants and readonly? What is difference between constants and readonly?

C# 112

Mid

Answer

Constant variables are declared and initialized at compile time. The value can't be changed afterwards. Readonly is used only when we want to assign the value at run
time.

Interview Coming Up? Check 112 C# Interview Questions

linkguru99.com

Q19: What is a Destructor in C#? What is a Destructor in C#?

C# 112

Mid
Answer

A Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called
internally for cleaning up. But sometimes it may be necessary to implement destructors manually.

Interview Coming Up? Check 112 C# Interview Questions

linksoftwaretestinghelp.com

See All 112 C# Q&A

Code Problems 26

Xamarin 83

Bootstrap 38

WebSockets 24
HTML5 55

ASP.NET Web API 33

ADO.NET 33

CSS 50

jQuery 51

Android 113

Q20: How encapsulation is implemented in C#? How encapsulation is implemented in C#?

C# 112

Mid

Answer

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member.

 Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be
accessed from outside the class.
 Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class
can access its private members. Even an instance of a class cannot access its private members.
 Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing
inheritance.

Interview Coming Up? Check 112 C# Interview Questions


linktutorialspoint.com

Q21: What is the output of the program below? Explain your answer. What is the output of the program below? Explain your answer.

C# 112

Mid

Details

Consider:

delegate void Printer();

static void Main()


{
List<Printer> printers = new List<Printer>();
int i=0;
for(; i < 10; i++)
{
printers.Add(delegate { Console.WriteLine(i); });
}

foreach (var printer in printers)


{
printer();
}
}
Solution
This program will output the number 10 ten times.

Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i is stored, rather than the value itself.
Therefore, after we exit the loop, the variable i has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.

Interview Coming Up? Check 112 C# Interview Questions

linktoptal.com

25 Redis Interview Questions (ANSWERED) For Web Developers

#Redis

Bootstrap 38

TypeScript 39
ASP.NET Web API 33

ASP.NET 60

WPF 46

Software Architecture 46

Reactive Programming 27

NoSQL 14

DevOps 39

OOP 53

Python 96

Ionic 29

SQL 56

Q22: Refactor the code Refactor the code

C# 112
Mid

Details
class ClassA
{
public ClassA() { }

public ClassA(int pValue) { }


}

// client program
class Program
{
static void Main(string[] args)
{
ClassA refA = new ClassA();
}
}
Is there a way to modify ClassA so that you can you call the constructor with parameters, when the Main method is called, without creating any other new instances
of the ClassA?

Solution

The this keyword is used to call other constructors, to initialize the class object. The following shows the implementation:

class ClassA
{
public ClassA() : this(10)
{ }

public ClassA(int pValue)


{ }
}

Interview Coming Up? Check 112 C# Interview Questions

linktoptal.com

See All 112 C# Q&A

Q23: What is lambda expressions in C#? What is lambda expressions in C#?

C# 112

Mid

Answer
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local
functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

Interview Coming Up? Check 112 C# Interview Questions

linkdocs.microsoft.com

Xamarin 83

ADO.NET 33
Entity Framework 57

ASP.NET Web API 33

Behavioral 112

Python 96

XML & XSLT 41

Software Testing 26

AngularJS 62

Ruby 84

Git 36

Design Patterns 45

Ionic 29

Q24: What is marshalling and why do we need it? What is marshalling and why do we need it?

C# 112
Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

Q25: What is difference between late binding and early binding in C#? What is difference between late binding and early binding in C#?

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

See All 112 C# Q&A

LINQ 35

Xamarin 83

Ruby on Rails 72

Design Patterns 45

Ruby 84

ADO.NET 33
Laravel 41

Entity Framework 57

WPF 46

React 164

XML & XSLT 41

TypeScript 39

Ionic 29

Q26: What is an Object Pool in .Net? What is an Object Pool in .Net?

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer


22+ Angular 6 Interview Questions to Stand Out in 2018

#Angular

Q27: Describe the accessibility modifier "protected internal". Describe the accessibility modifier "protected internal".

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

ASP.NET Web API 33

PHP 82

AngularJS 62

Data Structures 30

Java 147
Microservices 34

GraphQL 24

React 164

Xamarin 83

WebSockets 24
AWS 44

Web Security 58

Q28: What are pointer types in C#? What are pointer types in C#?

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

See All 112 C# Q&A

Q29: What is the use of conditional preprocessor directive in C#? What is the use of conditional preprocessor directive in C#?

C# 112
Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

Bootstrap 38

DevOps 39

ADO.NET 33

Android 113

Behavioral 112

PWA 22

Data Structures 30

NoSQL 14

.NET Core 51

Ruby 84

C# 112
Git 36

Code Problems 26

Q30: Can we have only “try” block without “catch” block in C#? Can we have only “try” block without “catch” block in C#?

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

Q31: Why to use lock statement in C#? Why to use lock statement in C#?

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

See All 112 C# Q&A


22 Essential WCF Interview Questions (SOLVED) That'll Make You Cry

#WCF

Data Structures 30

Android 113

ADO.NET 33

T-SQL 36

DevOps 39

WCF 33

MongoDB 82

jQuery 51

Design Patterns 45
Entity Framework 57

NoSQL 14

SQL 56

Q32: What is the output of the short program below? Explain your answer. What is the output of the short program below? Explain your answer.

C# 112

Senior

Details

Consider:

class Program {
static String location;
static DateTime time;

static void Main() {


Console.WriteLine(location == null ? "location is null" : location);
Console.WriteLine(time == null ? "time is null" : time.ToString());
}
}
Answer
Join FSC to see Answer to this Interview Question...

Join To Unlock Answer


Q33: What is the output of the program below? Explain your answer. What is the output of the program below? Explain your answer.

C# 112

Senior

Details

Consider:

class Program {
private static string result;

static void Main() {


SaySomething();
Console.WriteLine(result);
}

static async Task<string> SaySomething() {


await Task.Delay(5);
result = "Hello world!";
return “Something”;
}
}
Also, would the answer change if we were to replace await Task.Delay(5); with Thread.Sleep(5)? Why or why not?

Answer

Join FSC to see Answer to this Interview Question...


Join To Unlock Answer

Reactive Programming 27

AWS 44

Git 36

Questions to Ask 39

Vue.js 41

Code Problems 26

Flutter 68
Docker 55

ASP.NET MVC 33

Webpack 32

ASP.NET 60

Ionic 29

Q34: What is the output of the program below? What is the output of the program below?

C# 112

Senior

Details

Consider:

public class TestStatic {


public static int TestValue;

public TestStatic() {
if (TestValue == 0) {
TestValue = 5;
}
}
static TestStatic() {
if (TestValue == 0) {
TestValue = 10;
}

public void Print() {


if (TestValue == 5) {
TestValue = 6;
}
Console.WriteLine("TestValue : " + TestValue);

}
}

public void Main(string[] args) {

TestStatic t = new TestStatic();


t.Print();
}
Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer


See All 112 C# Q&A

Q35: What is the "yield" keyword used for in C#? What is the "yield" keyword used for in C#?

C# 112

Senior

Details

Consider:

IEnumerable<object> FilteredList()
{
foreach( object item in FullList )
{
if( IsItemInPartialList( item )
yield return item;
}
}
Could you explain what does the yield keyword do there?

Answer

Join FSC to see Answer to this Interview Question...

Join To Unlock Answer

Ruby on Rails 72

Angular 120
SOA & REST API 66

LINQ 35

C# 112

ASP.NET MVC 33

Entity Framework 57

DevOps 39

Web Security 58

Spring 87

Ruby 84

NoSQL 14

Q36: What interface should your data structure implement to make the "Where" method work? What interface should your data structure implement to make the "Where" method work?

C# 112

Senior

Answer

Join FSC to see Answer to this Interview Question...


Join To Unlock Answer

22 Dart Interview Questions (ANSWERED) Flutter Dev Must Know in 2020

#Flutter

Q37: What is jagged array in C#.Net and when to prefer jagged arrays over multi-dimensional arrays? What is jagged array in C#.Net and when to prefer jagged arrays over multi-dimensional arrays?

C# 112

Expert

Answer

Share this post to Unlock Answer to Expert Interview Question...

Share This Post To Unlock Expert Answers!

See All 112 C# Q&A


LINQ 35

MSMQ 16

Microservices 34

Entity Framework 57

CSS 50

PWA 22

React 164

Golang 49

WCF 33

XML & XSLT 41

Laravel 41

Java 147

MongoDB 82
Design Patterns 45

jQuery 51

Q38: What is a preprocessor directives in C#? What is a preprocessor directives in C#?

C# 112

Expert

Answer

Share this post to Unlock Answer to Expert Interview Question...

Share This Post To Unlock Expert Answers!

Q39: What are the benefits of a Deferred Execution in LINQ? What are the benefits of a Deferred Execution in LINQ?

C# 112

Expert

Answer

Share this post to Unlock Answer to Expert Interview Question...

http://a4academics.com/interview-questions/52-dot-net-interview-questions/417-c-oops-interview-questions-and-answers

Top 100 Basic and Advanced C# Interview Questions and Answers for Freshers and 2 - 4 years Experienced Dot Net developers and Testers
with sample code and best answers.

1) What is C-Sharp (C#)?


C# is a type-safe, managed and object oriented language, which is compiled by .Net framework for generating intermediate language (IL).

2) Explain the features of C#?


Below are some of the features supported in C# -

 Constructors and Destructors


 Properties
 Passing Parameters
 Arrays
 Main
 XML Documentation and
 Indexers

3) List some of the advantages of C#?


Below are the advantages of C# -

 Easy to learn
 Object oriented
 Component oriented
 Part of .NET framework

4) What are IDE’s provided by Microsoft for C# development?


Below are the IDE’s used for C# development –

 Visual Studio Express (VCE)


 Visual Studio (VS)
 Visual Web Developer

5) Explain the types of comments in C#?

Below are the types of comments in C# -


 Single Line Comment Eg : //
 Multiline Comments Eg: /* */
 XML Comments Eg : ///

6) Explain sealed class in C#?

Sealed class is used to prevent the class from being inherited from other classes. So “sealed” modifier also can be used with methods to avoid the
methods to override in the child classes.

7) Give an example of using sealed class in C#?

Below is the sample code of sealed class in C# -

class X {}

sealed class Y : X {}

Sealed methods –

class A

protected virtual void First() { }

protected virtual void Second() { }

}
class B : A

sealed protected override void First() {}

protected override void Second() { }

If any class inherits from class “B” then method – “First” will not be overridable as this method is sealed in class B.

Must Read - .Net Framework Interview Questions and Answers

8) List out the differences between Array and ArrayList in C#?

 Array stores the values or elements of same data type but arraylist stores values of different datatypes.
 Arrays will use the fixed length but arraylist does not uses fixed length like array.

9) Why to use “using” in C#?

“Using” statement calls – “dispose” method internally, whenever any exception occurred in any method call and in “Using” statement objects
are read only and cannot be reassignable or modifiable.

10) Explain namespaces in C#?

Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword can be used for
using the namespace in other namespace.

11) Why to use keyword “const” in C#? Give an example.


“Const” keyword is used for making an entity constant. We can’t reassign the value to constant.

Eg: const string _name = "Test";

12) What is the difference between “constant” and “readonly” variables in C#?

 “Const” keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is mandatory to constant variables.
 “readonly” variable value can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.

Must Read - ADO.Net Interview Questions and Answers

13) Explain “static” keyword in C#?

“Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If
the variable is made static then it will have a single instance and the value change is updated in this instance.

14) What is the difference between “dispose” and “finalize” variables in C#?

 Dispose - This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
 Finalize - This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.

15) How the exception handling is done in C#?

In C# there is a “try… catch” block to handle the error.

16) Can we execute multiple catch blocks in C#?

No. Once any exception is occurred it executes specific exception catch block and the control comes out.
17) Why to use “finally” block in C#?

“Finally” block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is
returned to catch block and at last “finally” block will be executed. So closing connection to database / releasing the file handlers can be kept in
“finally” block.

18) What is the difference between “finalize” and “finally” methods in C#?

 Finalize – This method is used for garbage collection. So before destroying an object this method is called as part of clean up activity.
 Finally – This method is used for executing the code irrespective of exception occurred or not.

19) What is the difference between “throw ex” and “throw” methods in C#?

 “throw ex” will replace the stack trace of the exception with stack trace info of re throw point.
 “throw” will preserve the original stack trace info.

20) Can we have only “try” block without “catch” block in C#?

Yes we can have only try block without catch block but we have to have finally block.

21) List out two different types of errors in C#?

Below are the types of errors in C# -

 Compile Time Error


 Run Time Error

22) Do we get error while executing “finally” block in C#?

Yes. We may get error in finally block.


23) Mention the assembly name where System namespace lies in C#?

Assembly Name – mscorlib.dll

24) What are the differences between static, public and void in C#?

 Static classes/methods/variables are accessible throughout the application without creating instance. Compiler will store the method address as an entry point.
 Public methods or variables are accessible throughout the application.
 Void is used for the methods to indicate it will not return any value.

Don't Miss - Database Interview Questions and Answers

25) What is the difference between “out” and “ref” parameters in C#?

“out” parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before it is used.

26) Explain Jagged Arrays in C#?

If the elements of an array is an array then it’s called as jagged array. The elements can be of different sizes and dimensions.

27) Can we use “this” inside a static method in C#?

No. We can’t use “this” in static method.

28) What are value types in C#?

Below are the list of value types in C# -


 decimal
 int
 byte
 enum
 double
 long
 float

Must Read - SQL Query Interview Questions and Answers

29) What are reference types in C#?

Below are the list of reference types in C# -

 class
 string
 interface
 object

30) Can we override private virtual method in C#?

No. We can’t override private virtual methods as it is not accessible outside the class.

31) Explain access modifier – “protected internal” in C#?

“protected internal” can be accessed in the same assembly and the child classes can also access these methods.
32) In try block if we add return statement whether finally block is executed in C#?

Yes. Finally block will still be executed in presence of return statement in try block.
33) What you mean by inner exception in C#?
Inner exception is a property of exception class which will give you a brief insight of the exception i.e, parent exception and child exception details.
34) Explain String Builder class in C#?
This will represent the mutable string of characters and this class cannot be inherited. It allows us to Insert, Remove, Append and Replace the characters.
“ToString()” method can be used for the final string obtained from StringBuilder. For example,

StringBuilder TestBuilder = new StringBuilder("Hello");

TestBuilder.Remove(2, 3); // result - "He"

TestBuilder.Insert(2, "lp"); // result - "Help"

TestBuilder.Replace('l', 'a'); // result - "Heap"

35) What is the difference between “StringBuilder” and “String” in C#?

 StringBuilder is mutable, which means once object for stringbuilder is created, it later be modified either using Append, Remove or Replace.
 String is immutable and it means we cannot modify the string object and will always create new object in memory of string type.

36) What is the difference between methods – “System.Array.Clone()” and “System.Array.CopyTo()” in C#?

 “CopyTo()” method can be used to copy the elements of one array to other.
 “Clone()” method is used to create a new array to contain all the elements which are in the original array.

37) How we can sort the array elements in descending order in C#?

“Sort()” method is used with “Reverse()” to sort the array in descending order.
Also Read - ASP.Net Interview Questions and Answers

38) Explain circular reference in C#?

This is a situation where in, multiple resources are dependent on each other and this causes a lock condition and this makes the resource to be
unused.

39) List out some of the exceptions in C#?

Below are some of the exceptions in C# -

 NullReferenceException
 ArgumentNullException
 DivideByZeroException
 IndexOutOfRangeException
 InvalidOperationException
 StackOverflowException etc.

40) Explain Generics in C#?

Generics in c# is used to make the code reusable and which intern decreases the code redundancy and increases the performance and type safety.
Namespace – “System.Collections.Generic” is available in C# and this should be used over “System.Collections” types.

41) Explain object pool in C#?

Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.

Also Read - ASP.Net MVC Interview Questions and Answers


42) What you mean by delegate in C#?

Delegates are type safe pointers unlike function pointers as in C++. Delegate is used to represent the reference of the methods of some return
type and parameters.

43) What are the types of delegates in C#?

Below are the uses of delegates in C# -

 Single Delegate
 Multicast Delegate
 Generic Delegate

44) What are the three types of Generic delegates in C#?

Below are the three types of generic delegates in C# -

 Func
 Action
 Predicate

45) What are the differences between events and delegates in C#?

Main difference between event and delegate is event will provide one more of encapsulation over delegates. So when you are using events
destination will listen to it but delegates are naked, which works in subscriber/destination model.

46) Can we use delegates for asynchronous method calls in C#?

Yes. We can use delegates for asynchronous method calls.


47) What are the uses of delegates in C#?
Below are the list of uses of delegates in C# -

 Callback Mechanism
 Asynchronous Processing
 Abstract and Encapsulate method
 Multicasting

48) What is Nullable Types in C#?


Variable types does not hold null values so to hold the null values we have to use nullable types. So nullable types can have values either null or
other values as well.
Eg: Int? mynullablevar = null;

49) Why to use “Nullable Coalescing Operator” (??) in C#?


Nullable Coalescing Operator can be used with reference types and nullable value types. So if the first operand of the expression is null then the
value of second operand is assigned to the variable. For example,
double? myFirstno = null;

double mySecno;

mySecno = myFirstno ?? 10.11;

50) What is the difference between “as” and “is” operators in C#?

 “as” operator is used for casting object to type or class.


 “is” operator is used for checking the object with type and this will return a Boolean value.
51) Define Multicast Delegate in C#?

A delegate with multiple handlers are called as multicast delegate. The example to demonstrate the same is given below

public delegate void CalculateMyNumbers(int x, int y);

int x = 6;

int y = 7;

CalculateMyNumbers addMyNumbers = new CalculateMyNumbers(FuncForAddingNumbers);

CalculateMyNumbers multiplyMyNumbers = new CalculateMyNumbers(FuncForMultiplyingNumbers);

CalculateMyNumbers multiCast = (CalculateMyNumbers)Delegate.Combine (addMyNumbers, multiplyMyNumbers);

multiCast.Invoke(a,b);

52) What is the difference between CType and Directcast in C#?

 CType is used for conversion between type and the expression.


 Directcast is used for converting the object type which requires run time type to be the same as specified type.

53) Is C# code is unmanaged or managed code?

C# code is managed code because the compiler – CLR will compile the code to Intermediate Language.

54) Why to use lock statement in C#?

Lock will make sure one thread will not intercept the other thread which is running the part of code. So lock statement will make the thread wait,
block till the object is being released.
55) Explain Hashtable in C#?

It is used to store the key/value pairs based on hash code of the key. Key will be used to access the element in the collection. For example,

Hashtable myHashtbl = new Hashtable();


myHashtbl.Add("1", "TestValue1");
myHashtbl.Add("2", "TestValue2");

56) How to check whether hash table contains specific key in C#?

Method – “ContainsKey” can be used to check the key in hash table. Below is the sample code for the same –

Eg: myHashtbl.ContainsKey("1");

57) What is enum in C#?

enum keyword is used for declaring an enumeration, which consists of named constants and it is called as enumerator lists. Enums are value
types in C# and these can’t be inherited. Below is the sample code of using Enums

Eg: enum Fruits { Apple, Orange, Banana, WaterMelon};

58) Which are the loop types available in C#?

Below are the loop types in C# -

For
While
Do.. While
59) What is the difference between “continue” and “break” statements in C#?

 “continue” statement is used to pass the control to next iteration. This statement can be used with – “while”, “for”, “foreach” loops.
 “break” statement is used to exit the loop.

60) Write a sample code to write the contents to text file in C#?

Below is the sample code to write the contents to text file –

Using System.IO;

File.WriteAllText(”mytextfilePath”, “MyTestContent”);

61) What you mean by boxing and unboxing in C#?

Boxing – This is the process of converting from value type to reference type. For example,
int myvar = 10;

object myObj = myvar;

UnBoxing – It’s completely opposite to boxing. It’s the process of converting reference type to value type. For example,
int myvar2 = (int)myObj;

62) Explain Partial Class in C#?

Partial classes concept added in .Net Framework 2.0 and it allows us to split the business logic in multiple files with the same class name along
with “partial” keyword.

63) Explain Anonymous type in C#?


This is being added in C# 3.0 version. This feature enables us to create an object at compile time. Below is the sample code for the same –
Var myTestCategory = new { CategoryId = 1, CategoryName = “Category1”};

64) Name the compiler of C#?

C# Compiler is – CSC.

65) Explain the types of unit test cases?

Below are the list of unit test case types –

 Positive Test cases


 Negative Test cases
 Exception Test cases

66) Explain Copy constructor in C#?

If the constructor contains the same class in the constructor parameter then it is called as copy constructor.

class MyClass

public string prop1, prop2;

public MyClass(string a, string b)

prop1 = a;
prop2 = b;

public MyClass(MyClass myobj) // Copy Constructor

prop1 = myobj.prop1;

prop2 = myobj.prop2;

67) Explain Static constructor in C#?

If the constructor is declared as static then it will be invoked only once for all number of instances of a class. Static constructor will initialize the
static fields of a class.

class MyClass

public string prop1, prop2;

public MyClass(string a, string b)

{
prop1 = a;

prop2 = b;

Static MyClass()

Console.WriteLine(“Static Constr Test”);

public MyClass(MyClass myobj) // Copy Constructor

prop1 = myobj.prop1;

prop2 = myobj.prop2;

68) Which string method is used for concatenation of two strings in c#?

“Concat” method of String class is used to concatenate two strings. For example,
string.Concat(firstStr, secStr)

69) Explain Indexers in C#?

Indexers are used for allowing the classes to be indexed like arrays. Indexers will resemble the property structure but only difference is indexer’s
accessors will take parameters. For example,

class MyCollection<T>

private T[] myArr = new T[100];

public T this[int t]

get

return myArr[t];

set

myArr[t] = value;

}
}

70) What are the collection types can be used in C#?

Below are the collection types in C# -

 ArrayList
 Stack
 Queue
 SortedList
 HashTable
 Bit Array

71) Explain Attributes in C#?

 Attributes are used to convey the info for runtime about the behavior of elements like – “methods”, “classes”, “enums” etc.
 Attributes can be used to add metadata like – comments, classes, compiler instruction etc.

72) List out the pre defined attributes in C#?

Below are the predefined attributes in C# -

 Conditional
 Obsolete
 Attribute Usage

73) What is Thread in C#?


Thread is an execution path of a program. Thread is used to define the different or unique flow of control. If our application involves some time
consuming processes then it’s better to use Multithreading., which involves multiple threads.

74) List out the states of a thread in C#?

Below are the states of thread –

 Unstarted State
 Ready State
 Not Runnable State
 Dead State

75) Explain the methods and properties of Thread class in C#?

Below are the methods and properties of thread class –

 CurrentCulture
 CurrentThread
 CurrentContext
 IsAlive
 IsThreadPoolThread
 IsBackground
 Priority

76) What is a class ?

A class is the generic definition of what an object is. A Class describes all the attributes of the object, as well as the methods that implement the
behavior of the member object. In other words, class is a template of an object. For ease of understanding a class, we will look at an example. In
the class Employee given below, Name and Salary are the attributes of the class Person. The Setter and Getter methods are used to
store and fetch data from the variable.

public class Employee


{

private String name;

private String Salary;

public String getName()

return name;

public void setName(String name)

this.name = name;

public String getSalary ()

return Salary;
}

public void setSalary (String Salary)

this. Salary = Salary;

77) What is an Object?


An object is an instance of a class. It contains real values instead of variables. For example, let us create an instance of the class Employee
called “John”.
Employee John= new Employee();

Now we can access all the methods in the class “Employee” via object “John” as shown below.

John.setName(“XYZ”);

78) What are the Access Modifiers in C# ?


Different Access Modifier are - Public, Private, Protected, Internal, Protected Internal
 Public – When a method or attribute is defined as Public, it can be accessed from any code in the project. For example, in the above Class
“Employee” getName() and setName() are public.
 Private - When a method or attribute is defined as Private, It can be accessed by any code within the containing class only. For example, in the
above Class “Employee” attributes name and salary can be accessed within the Class Employee Only. If an attribute or class is defined
without access modifiers, it's default access modifier will be private.
 Protected - When attribute and methods are defined as protected, it can be accessed by any method in the inherited classes and any
method within the same class. The protected access modifier cannot be applied to classes and interfaces. Methods and fields in
a interface can't be declared protected.
 Internal – If an attribute or method is defined as Internal, access is restricted to classes within the current project assembly.
 Protected Internal – If an attribute or method is defined as Protected Internal, access is restricted to classes within the current project assembly
and types derived from the containing class.

79) Explain Static Members in C# ?

If an attribute's value had to be same across all the instances of the same class, the static keyword is used. For example, if the Minimum salary
should be set for all employees in the employee class, use the following code.

private static double MinSalary = 30000;

To access a private or public attribute or method in a class, at first an object of the class should be created. Then by using the object instance of
that class, attributes or methods can be accessed. To access a static variable, we don't want to create an instance of the class containing the static
variable. We can directly refer that static variable as shown below.

double var = Employee.MinSalary ;

80) What is Reference Type in C# ?

Let us explain this with the help of an example. In the code given below,
Employee emp1;

Employee emp2 = new Employee();

emp1 = emp2;

Here emp2 has an object instance of Employee Class. But emp1 object is set as emp2. What this means is that the object emp2 is referred in
emp1, rather than copying emp2 instance into emp1. When a change is made in emp2 object, corresponding changes can be seen in emp1
object.

81) Define Property in C# ?

Properties are a type of class member, that are exposed to the outside world as a pair of Methods. For example, for the static field Minsalary, we
will Create a property as shown below.

private double minimumSalary;

public static double MinSalary

get

return minimumSalary;
}

set

minimumSalary = value;

So when we execute the following lines code


double minSal = Employee.MinSalary;

get Method will get triggered and value in minimumSalary field will be returned. When we execute,
Employee. MinSalary = 3000;

set Method will get triggered and value will be stored in minimumSalary field.

82) Explain Overloading in C# ?

When methods are created with the same name, but with different signature its called overloading. For example, WriteLine method in console
class is an example of overloading. In the first instance, it takes one variable. In the second instance, “WriteLine” method takes two variable.
Console.WriteLine(x);

Console.WriteLine("The message is {0}", Message);

Different types of overloading in C# are

 Constructor overloading
 Function overloading
 Operator overloading

83) What is Constructor Overloading in C# .net ?

In Constructor overloading, n number of constructors can be created for the same class. But the signatures of each constructor should vary. For
example

public class Employee

public Employee()

{}

public Employee(String Name)

{}

}
84) What is Function Overloading in C# .net ?

In Function overloading, n number of functions can be created for the same class. But the signatures of each function should vary. For example

public class Employee

public void Employee()

{}

public void Employee(String Name)

{}

85) What is Operator Overloading in C# .net ?

We had seen function overloading in the previous example. For operator Overloading, we will have a look at the example given below. We had
defined a class rectangle with two operator overloading methods.

class Rectangle

{
private int Height;

private int Width;

public Rectangle(int w,int h)

Width=w;

Height=h;

public static bool operator >(Rectangle a,Rectangle b)

return a.Height > b.Height ;

public static bool operator <(Rectangle a,Rectangle b)


{

return a.Height < b.Height ;

Let us call the operator overloaded functions from the method given below. When first if condition is triggered, the first overloaded function in
the rectangle class will be triggered. When second if condition is triggered, the second overloaded function in the rectangle class will be
triggered.

public static void Main()

Rectangle obj1 =new Rectangle();

Rectangle obj2 =new Rectangle();

if(obj1 > obj2)

Console.WriteLine("Rectangle1 is greater than Rectangle2");


}

if(obj1 < obj2)

Console.WriteLine("Rectangle1 is less than Rectangle2");

86) What is Data Encapsulation ?

Data Encapsulation is defined as the process of hiding the important fields from the end user. In the above example, we had used getters and
setters to set value for MinSalary. The idea behind this is that, private field “minimumSalary” is an important part of our classes. So if we give a
third party code to have complete control over the field without any validation, it can adversely affect the functionality. This is inline with the
OOPS Concept that an external user should know about the what an object does. How it does it, should be decided by the program. So if a user
set a negative value for MinSalary, we can put a validation in the set method to avoid negative values as shown below

set

if(value > 0)
{

minSalary = value;

87) Explain Inheritance in C# ?


In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects. In inheritance, there will be two classes - base
class and derived classes. A class can inherit attributes and methods from existing class called base class or parent class. The class which inherits
from a base class is called derived classes or child class. For more clarity on this topic, let us have a look at 2 classes shown below. Here Class
Car is Base Class and Class Ford is derived class.
class Car

public Car()

Console.WriteLine("Base Class Car");

}
public void DriveType()

Console.WriteLine("Right Hand Drive");

class Ford : Car

public Ford()

Console.WriteLine("Derived Class Ford");

}
public void Price()

Console.WriteLine("Ford Price : 100K $");

When we execute following lines of code ,


Ford CarFord = new Ford();

CarFord.DriveType();

CarFord.Price();

Output Generated is as given below.


Base Class Car

Derived Class Ford

Right Hand Drive


Ford Price : 100K $

What this means is that, all the methods and attributes of Base Class car are available in Derived Class Ford. When an object of class Ford is
created, constructors of the Base and Derived class get invoked. Even though there is no method called DriveType() in Class Ford, we are able to
invoke the method because of inheriting Base Class methods to derived class.

88) Can Multiple Inheritance implemented in C# ?

In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, use interface.

89) What is Polymorphism in C# ?

The ability of a programming language to process objects in different ways depending on their data type or class is known as
Polymorphism. There are two types of polymorphism

 Compile time polymorphism. Best example is Overloading


 Runtime polymorphism. Best example is Overriding

90) Explain the use of Virtual Keyword in C# ?

When we want to give permission to a derived class to override a method in base class, Virtual keyword is used. For example. lets us look at the
classes Car and Ford as shown below.

class Car

public Car()
{

Console.WriteLine("Base Class Car");

public virtual void DriveType()

Console.WriteLine("Right Hand Drive");

class Ford : Car

public Ford()

{
Console.WriteLine("Derived Class Ford");

public void Price()

Console.WriteLine("Ford Price : 100K $");

public override void DriveType()

Console.WriteLine("Right Hand ");

When following lines of code get executed

Car CarFord = new Car();


CarFord.DriveType();

CarFord = new Ford();

CarFord.DriveType();

Output is as given below.

Base Class Car

Right Hand Drive

Base Class Car

Derived Class Ford

Right Hand

91) What is overriding in c# ?

To override a base class method which is defined as virtual, Override keyword is used. In the above example, method DriveType is overridden in
the derived class.

92) What is Method Hiding in C# ?


If the derived class doesn't want to use methods in the base class, derived class can implement it's own version of the same method with same
signature. For example, in the classes given below, DriveType() is implemented in the derived class with same signature. This is called Method
Hiding.
class Car

public void DriveType()

Console.WriteLine("Right Hand Drive");

class Ford : Car

public void DriveType()

{
Console.WriteLine("Right Hand ");

93) What is Abstract Class in C#?


If we don't want a class to be instantiated, define the class as abstract. An abstract class can have abstract and non abstract classes. If a method is
defined as abstract, it must be implemented in derived class. For example, in the classes given below, method DriveType is defined as abstract.
abstract class Car

public Car()

Console.WriteLine("Base Class Car");

public abstract void DriveType();

}
class Ford : Car

public void DriveType()

Console.WriteLine("Right Hand ");

Method DriveType get implemented in derived class.

94) What is Sealed Classes in c# ?


If a class is defined as Sealed, it cannot be inherited in derived class. Example of a sealed class is given below.
public sealed class Car

public Car()
{

Console.WriteLine("Base Class Car");

public void DriveType()

Console.WriteLine("Right Hand ");

95) What is an Interface in C# ?

An interface is similar to a class with method signatures. There wont be any implementation of the methods in an Interface. Classes which
implement interface should have an implementation of methods defined in the abstract class.

96) What is a Constructor in C# ?

Constructor is a special method that get invoked/called automatically, whenever an object of a given class gets instantiated. In our class car,
constructor is defined as shown below
public Car()

Console.WriteLine("Base Class Car");

When ever an instance of class car is created from the same class or its derived class(Except Few Scenarios), Constructor get called and
sequence of code written in the constructor get executed.

interface Breaks

void BreakType();

interface Wheels

void WheelType();
}

class Ford : Breaks, Wheels

public Ford()

Console.WriteLine("Derived Class Ford");

public void Price()

Console.WriteLine("Ford Price : 100K $");

public void BreakType()


{

Console.WriteLine("Power Break");

public void WheelType()

Console.WriteLine("Bridgestone");

97) What is a Destructor in C# ?

Destructor is a special method that get invoked/called automatically whenever an object of a given class gets destroyed. Main idea behind using
destructor is to free the memory used by the object.

https://www.c-sharpcorner.com/UploadFile/puranindia/C-Sharp-interview-questions/
Here are top 50 C# interview questions and answers. These C# interview questions are for both beginners and professional C# developers.

1. What is C#?
C# is a computer programming language. C# was developed by Microsoft in 2000 to provide a modern general-purpose programming language
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, serverless applications, Web
applications, native iOS and Android apps, AI and machine learning software, and blockchain applications.

C# with the help of Visual Studio IDE provides a rapid application development. C# is a modern, object-oriented, simple, versatile, and
performance-oriented programming language. C# is developed based on the best features and use cases of several programming languages
including C++, Java, Pascal, and SmallTalk.

C# syntaxes are like C++. .NET and the C# library is similar to Java. C# supports modern object-oriented programming language features
including Abstraction, Encapsulation, Polymorphism, and Inheritance. C# is a strongly typed language and most types are inherited by the
Object class.

C# supports concepts of classes and objects. Classes have members such as fields, properties, events, and methods. Here is a detailed article
on C# and OOP.

C# is versatile, modern, and supports modern programming needs. Since its inception, C# language has gone through various upgrades. The
latest version of C# is v8.0. Here is a detailed series on C# 8 - Learn C# 8.0 Step by Step.
2. What is an object in C#?
C# language is an object-oriented programming language. Classes are the foundation of C#. A class is a template that defines what a data
structure will look like, and how data will be stored, managed, and transferred. A class has fields, properties, methods, and other members.

While classes are concepts, objects are real. Objects are created using class instances. A class defines the type of an object. Objects store
real values in computer memory.

Any real-world entity which has some certain characteristics or that can perform some work is called an Object. This object is also called
an instance, i.e. a copy of an entity in a programming language. Objects are instances of classes.

For example, we need to create a program that deals with cars. We need to create an entity for the car. Let’s call it a class, Car. A car has four
properties, i.e., model, type, color, and size.

To represent a car in programming, we can create a class, Car, with four properties, Model, Type, Color, and Size. These are called members
of a class. A class has several types of members, constructors, fields, properties, methods, delegates, and events. A class member can be
private, protected, and pubic. Since these properties may be accessed outside the class, these can be public.

An object is an instance of a class. A class can have as many instances as needed. For example, Honda Civic is an instance of Car. In real
programming, Honda Civic is an object. Honda Civic is an instance of the class Car. The Model, Type, Color, and Size properties of Honda
Civic are Civic, Honda, Red, 4 respectively. BMW 330, Toyota Carolla, Ford 350, Honda CR4, Honda Accord, and Honda Pilot are some more
examples of objects of Car.

To learn more about real-world examples of objects and instance, please read, Object Oriented Programming with Real World Scenario.
3. What is Managed or Unmanaged Code?
Managed Code

“Managed code is the code that is developed using the .NET framework and its supported programming languages such as C# or VB.NET.
Managed code is directly executed by the Common Language Runtime (CLR or Runtime) and its lifecycle including object creation, memory
allocation, and object disposal is managed by the Runtime. Any language that is written in .NET Framework is managed code".

Unmanaged Code

The code that is developed outside of the .NET framework is known as unmanaged code.

“Applications that do not run under the control of the CLR are said to be unmanaged. Languages such as C or C++ or Visual Basic are
unmanaged.
The object creation, execution, and disposal of unmanaged code is directly managed by the programmers. If programmers write bad code, it
may lead to memory leaks and unwanted resource allocations.”

The .NET Framework provides a mechanism for unmanaged code to be used in managed code and vice versa. The process is done with the
help of wrapper classes.

4. What is Boxing and Unboxing in C#?


Boxing and Unboxing both are used for type conversions.

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

1. // Boxing
2. int anum = 123;
3. Object obj = anum;
4. Console.WriteLine(anum);
5. Console.WriteLine(obj);
The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.

1. // Unboxing
2. Object obj2 = 123;
3. int anum2 = (int)obj;
4. Console.WriteLine(anum2);
5. Console.WriteLine(obj);
5. What is the difference between a struct and a class in C#?
Class and struct are both user-defined data types, but have some major differences:

Struct

 The struct is a value type in C# and it inherits from System.Value Type.


 Struct is usually used for smaller amounts of data.
 Struct can’t be inherited from other types.
 A structure can't be abstract.
 No need to create an object with a new keyword.
 Do not have permission to create any default constructor.
Class

 The class is a reference type in C# and it inherits from the System.Object Type.
 Classes are usually used for large amounts of data.
 Classes can be inherited from other classes.
 A class can be an abstract type.
 We can create a default constructor.

Read the following articles to learn more about structs vs classes, Struct and Class Differences in C#.

6. What is the difference between Interface and Abstract Class in C#?


Here are some of the common differences between an interface and an abstract class in C#.

 A class can implement any number of interfaces but a subclass can at most use only one abstract class.
 An abstract class can have non-abstract methods (concrete methods) while in case of interface, all the methods have to be abstract.
 An abstract class can declare or use any variables while an interface is not allowed to do so.
 In an abstract class, all data members or functions are private by default while in an interface all are public, we can’t change them
manually.
 In an abstract class, we need to use abstract keywords to declare abstract methods, while in an interface we don’t need to use that.
 An abstract class can’t be used for multiple inheritance while the interface can be used as multiple inheritance.
 An abstract class use constructor while in an interface we don’t have any type of constructor.

To learn more about the difference between an abstract class and an interface, visit Abstract Class vs Interface.

7. What is enum in C#?


An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an
enumeration. It is a primitive data type that is user-defined.
An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int it has to be cast.

An enum is used to create numeric constants in the .NET framework. All the members of enum are enum type. There must be a numeric value
for each enum type.

The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive
enumerator is increased by 1.

1. enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};


Some points about enum,

 Enums are enumerated data types in c#.


 Enums are not for the end-user, they are meant for developers.
 Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of
another type even though the underlying value of their members is the same.
 Enumerations (enums) make your code much more readable and understandable.
 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.
 Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
 Enums are value types and are created on the stack and not on the heap.

For more details follow the link, Enums in C#.

8. 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.
Eg. Break Statement

1. using System;
2. using System.Collections;
3. using System.Linq;
4. using System.Text;
5. namespace break_example {
6. Class brk_stmt {
7. public static void main(String[] args) {
8. for (int i = 0; i <= 5; i++) {
9. if (i == 4) {
10. break;
11. }
12. Console.WriteLine("The number is " + i);
13. Console.ReadLine();
14. }
15. }
16. }
17. }
Output

The number is 0;

The number is 1;

The number is 2;

The number is 3;
Eg. Continue Statement

1. using System;
2. using System.Collections;
3. using System.Linq;
4. using System.Text;
5. namespace continue_example {
6. Class cntnu_stmt {
7. public static void main(String[] {
8. for (int i = 0; i <= 5; i++) {
9. if (i == 4) {
10. continue;
11. }
12. Console.WriteLine(“The number is "+ i);
13. Console.ReadLine();
14. }
15. }
16. }
17. }
Output

The number is 1;

The number is 2;

The number is 3;
The number is 5;

For more details, check out the following link: Break and Continue Statements in C#

9. What is the difference between constant and readonly in C#?


Const is nothing but "constant", a variable of which the value is constant but at compile time. 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.

Example

We have a Test Class in which we have two variables, one is readonly and the other is a constant.

1. class Test {
2. readonly int read = 10;
3. const int cons = 10;
4. public Test() {
5. read = 100;
6. cons = 100;
7. }
8. public void Check() {
9. Console.WriteLine("Read only : {0}", read);
10. Console.WriteLine("const : {0}", cons);
11. }
12. }

Here, I was trying to change the value of both the variables in constructor, but when I try to change the constant, it gives an error to change
their value in the block that I have to call at run time.

Finally, remove that line of code from class and call this Check() function like in the following code snippet:

1. class Program {
2. static void Main(string[] args) {
3. Test obj = new Test();
4. obj.Check();
5. Console.ReadLine();
6. }
7. }
8. class Test {
9. readonly int read = 10;
10. const int cons = 10;
11. public Test() {
12. read = 100;
13. }
14. public void Check() {
15. Console.WriteLine("Read only : {0}", read);
16. Console.WriteLine("const : {0}", cons);
17. }
18. }

Output

Learn more about const and readonly here: Difference Between Const, ReadOnly and Static ReadOnly in C#.

10. What is the difference between ref and out keywords?


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.

The out keyword passes arguments by reference. This is very similar to the ref keyword.
To learn more about ref and out keywords, read the following article: Ref Vs Out Keywords in C#

11. Can “this” be used within a static method?


We can't use 'this' in a static method because the keyword 'this' returns a reference to the current instance of the class containing it. Static
methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and are called with
the name of a class, not by instance, so we can’t use this keyword in the body of static Methods. However, in the case of Extension Methods,
we can use the parameters of the function.
Let’s have a look at the “this” keyword.
The "this" keyword in C# is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first
parameter of the type class in which it is defined.

Learn more here: The this Keyword In C#.

12. What are Properties in C#?


C# properties are members of a C# class that provide a flexible mechanism to read, write or compute the values of private fields, in other
words, by using properties, we can access private fields and set their values. Properties in C# are always public data members. C# properties
use get and set methods, also known as accessors, to access and assign values to private fields.

What are accessors?

The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property. The set
accessor specifies that we can assign a value to a private field in a property. Without the set accessor property, it is like a readonly field. With
the 'get' accessor we can access the value of the private field. In other words, it returns a single value. A Get accessor specifies that we can
access the value of a field publically.

We have three types of properties: Read/Write, ReadOnly, and WriteOnly. Let's see each one by one.

Learn more here: Property in C#

13. What are extension methods in C#?


Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the
original type.

An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

How to use extension methods?

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first
parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

For more details on extension methods, you can read these articles, Extension Methods in C#.

14. What is the difference between the dispose and finalize methods in C#?
In finalize and dispose, both methods are used to free unmanaged resources.

Finalize

 Finalize is used to free unmanaged resources that are not in use, like files, database connections in the application domain and more.
These are resources held by an object before that object is destroyed.
 In the Internal process, it is called by Garbage Collector and can’t be called manual by user code or any service.
 Finalize belongs to System.Object class.
 Implement it when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage
collection happens.

Dispose

 Dispose is also used to free unmanaged resources that are not in use like files, database connections in the Application domain at any
time.
 Dispose is explicitly called by manual user code.
 If we need to use the dispose method, we must implement that class via IDisposable interface.
 It belongs to IDisposable interface.
 Implement this when you are writing a custom class that will be used by other users.

For more details follow this link, Back To Basics - Dispose Vs Finalize.

15. What is the difference between String and StringBuilder in C#?


StringBuilder and string are both used to string values, but both have many differences on the bases of instance creation and also in
performance.

String

A string is an immutable object. Immutable is when we create string objects in code so we cannot modify or change that object in any
operations like insert new value, replace or append any value with the existing value in a string object. When we have to do some operations to
change string simply it will dispose of the old value of string object and it will create a new instance in memory for hold the new value in a string
object, for example:
Note

 It’s an immutable object that holds a string value.


 Performance-wise, string is slow because it creates a new instance to override or change the previous value.
 String belongs to the System namespace.

StringBuilder

System.Text.Stringbuilder is a mutable object which also holds the string value, mutable means once we create a System.Text.Stringbuilder
object. We can use this object for any operation like insert value in an existing string with insert functions also replace or append without
creating a new instance of System.Text.Stringbuilder for every time so it’s using the previous object. That way, it works fast compared to the
System.String. Let’s see an example to understand System.Text.Stringbuilder.
Note

 StringBuilder is a mutable object.


 Performance-wise StringBuilder is very fast because it will use the same instance of StringBuilder object to perform any operation like
inserting a value in the existing string.
 StringBuilder belongs to System.Text.Stringbuilder namespace.

For more details, read the following article, Comparison of String and StringBuilder in C#.

16. What are delegates in C# and the uses of delegates?


A Delegate is an abstraction of one or more function pointers (as existed in C++; the explanation about this is out of the scope of this article).
The .NET has implemented the concept of function pointers in the form of delegates. With delegates, you can treat a function as data.
Delegates allow functions to be passed as parameters, returned from a function as a value and stored in an array. Delegates have the following
characteristics:

 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.
The delegate contains a couple of useful fields. The first one holds a reference to an object, and the second holds a method pointer. When you
invoke the delegate, the instance method is called on the contained reference. However, if the object reference is null then the runtime
understands this to mean that the method is a static method. Moreover, invoking a delegate syntactically is the exact same as calling a regular
function. Therefore, delegates are perfect for implementing callbacks.

Why Do We Need Delegates?

Historically, the Windows API made frequent use of C-style function pointers to create callback functions. Using a callback, programmers were
able to configure one function to report back to another function in the application. So the objective of using a callback is to handle button-
clicking, menu-selection, and mouse-moving activities. But the problem with this traditional approach is that the callback functions were not
type-safe. In the .NET framework, callbacks are still possible using delegates with a more efficient approach. Delegates maintain three
important pieces of information:

 The parameters of the method.


 The address of the method it calls.
 The return type of the method.

A delegate is a solution for situations in which you want to pass methods around to other methods. You are so accustomed to passing data to
methods as parameters that the idea of passing methods as an argument instead of data might sound a little strange. However, there are
cases in which you have a method that does something, for instance, invoking some other method. You do not know at compile time what this
second method is. That information is available only at runtime, hence Delegates are the device to overcome such complications.

Learn more about Delegates and Events in C# .NET

17. What are sealed classes in C#?


Sealed classes are used to restrict the inheritance feature of object-oriented programming. Once a class is defined as a sealed class, the class
cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of the
sealed class. If a class is derived from a sealed class then the compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

The following class definition defines a sealed class in C#:

1. // Sealed class
2. sealed class SealedClass
3. {
4. }

Learn more about sealed classes here: Sealed Classes in C#

18. What are partial classes?


A partial class is only used to split the definition of a class in two or more classes in the same source code file or more than one source file. You
can create a class definition in multiple files, but it will be compiled as one class at run time. Also, when you create an instance of this class,
you can access all the methods from all source files with the same object.

Partial Classes can be created in the same namespace. It isn't possible to create a partial class in a different namespace. So use the “partial”
keyword with all the class names that you want to bind together with the same name of a class in the same namespace. Let’s see an example:
To learn about partial classes, visit Partial Classes in C# With Real Example.

19. What is boxing and unboxing in C#?


Boxing and Unboxing are both used for type converting, but have some differences:
Boxing

Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type.
When the CLR boxes a value means when CLR converting a value type to Object Type, it wraps the value inside a System.Object and stores it
on the heap area in the application domain.

Example

Unboxing

Unboxing is also a process that is used to extract the value type from the object or any implemented interface type. Boxing may be done
implicitly, but unboxing has to be explicit by code.

Example:
The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

To learn more about boxing and unboxing, visit Boxing and Unboxing in C#.

20. What is IEnumerable<> in C#?


IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be
enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in
System.Collections.Generic namespace like List<> and more.

In System.Collections.Generic.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator
provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods if we don’t have this
interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.
For more details, visit Implement IEnumerable Interface in C#.

21. What is the difference between late binding and early binding in C#?
Early Binding and Late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object-oriented programming that
allows a language to use the same name in different forms. For example, a method named Add can add integers, doubles, and decimals.

Polymorphism we have 2 different types to achieve that:

 Compile Time also known as Early Binding or Overloading.


 Run Time is also known as Late Binding or Overriding.

Compile Time Polymorphism or Early Binding

In Compile time polymorphism or Early Binding, we will use multiple methods with the same name but different types of parameters, or maybe
the number of parameters. Because of this, we can perform different-different tasks with the same method name in the same class which is
also known as Method overloading.

See how we can do that in the following example:


Run Time Polymorphism or Late Binding

Run time polymorphism is also known as late binding. In Run Time Polymorphism or Late Binding, we can use the same method names with
the same signatures, which means the same type or the same number of parameters, but not in the same class because the compiler doesn’t
allow for that at compile time. Therefore, we can use that bind at run time in the derived class when a child class or derived class object will be
instantiated. That’s why we call it Late Binding. We have to create my parent class functions as partial and in driver or child class as override
functions with the override keyword.

Example
Learn more here, Understanding Polymorphism in C#.

22. What are the differences between IEnumerable and IQueryable?


Before we go into the differences, let's learn what the IEnumerable and IQueryable are.
IEnumerable
Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable, etc. that can be enumerated.
The generic version of this interface is IEnumerable<T>, which a parent interface of all generic collections class in System.Collections.Generic
namespace, like List<> and more.
IQueryable
As per MSDN, the IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers
that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on
the provider's data source.
The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated.
Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree"
is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying
data source. Queries that do not return enumerable results are executed when the Execute method is called.

Learn more here: IEnumerable vs IQuerable.


23. What happens if the inherited interfaces have conflicting method names?
If we implement multiple interfaces in the same class with conflict method names, we don’t need to define all. 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 have to use the interface name before the method name to remove this method confiscation. Let’s see an example:

1. interface testInterface1 {
2. void Show();
3. }
4. interface testInterface2 {
5. void Show();
6. }
7. class Abc: testInterface1,
8. testInterface2 {
9. void testInterface1.Show() {
10. Console.WriteLine("For testInterface1 !!");
11. }
12. void testInterface2.Show() {
13. Console.WriteLine("For testInterface2 !!");
14. }
15. }
Now see how to use these in a class:

1. class Program {
2. static void Main(string[] args) {
3. testInterface1 obj1 = new Abc();
4. testInterface1 obj2 = new Abc();
5. obj1.Show();
6. obj2.Show();
7. Console.ReadLine();
8. }
9. }
Output

For one more example follow the link: Inherit Multiple Interfaces and They have Conflicting Method Name

24. What are the Arrays in C#?


In C#, an array index starts at zero. That means the first item of an array starts at the 0th position. The position of the last item on an array will
total the number of items - 1. So if an array has 10 items, the last 10th item is in the 9th position.

In C#, arrays can be declared as fixed-length or dynamic.

A fixed-length array can store a predefined number of items.

A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare
an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.
Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest dynamic array of integer types that do
not have a fixed size.

int[] intArray;

As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket ([]) and the
name of the array.

The following code snippet declares an array that can store 5 items only starting from index 0 to 4.

1. int[] intArray;
2. intArray = new int[5];

The following code snippet declares an array that can store 100 items starting from index 0 to 99.
1. int[] intArray;
2. intArray = new int[100];

Learn more about Arrays in C#: Working with Arrays In C#

25. What is the Constructor Chaining in C#?


Constructor chaining is a way to connect two or more classes in a relationship as Inheritance. In Constructor Chaining, every child class
constructor is mapped to a parent class Constructor implicitly by base keyword, so when you create an instance of the child class, it will call the
parent’s class Constructor. Without it, inheritance is not possible.

For more examples, follow the link: Constructors In C#


26. 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 an Array copies only the elements of the Array, whether they
are 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 that the references in the original Array point to.

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. The code listed in Listing 9 copies contents of an integer array to an array of object types.

Learn more about arrays here, Working with Arrays in C#.

27. Can Multiple Catch Blocks be executed in C#?


We can use multiple catch blocks with a try statement. Each catch block can catch a different exception. The following code example shows
how to implement multiple catch statements with a single try statement.

1. using System;
2. class MyClient {
3. public static void Main() {
4. int x = 0;
5. int div = 0;
6. try {
7. div = 100 / x;
8. Console.WriteLine("Not executed line");
9. } catch (DivideByZeroException de) {
10. Console.WriteLine("DivideByZeroException");
11. } catch (Exception ee) {
12. Console.WriteLine("Exception");
13. } finally {
14. Console.WriteLine("Finally Block");
15. }
16. Console.WriteLine("Result is {0}", div);
17. }
18. }

To learn more about Exception Handling in C#, please visit, Exception Handling in C#.

28. What are Singleton Design Patterns and how to implement them in C#?
What is a Singleton Design Pattern?

1. Ensures a class has only one instance and provides a global point of access to it.
2. A Singleton is a class that only allows a single instance of itself to be created and usually gives simple access to that instance.
3. Most commonly, singletons don't allow any parameters to be specified when creating the instance since the second request of an
instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same
parameter then the factory pattern is more appropriate.)
4. There are various ways to implement the Singleton Pattern in C#. The following are the common characteristics of a Singleton Pattern.

o A single constructor, that is private and parameterless.


o The class is sealed.
o A static variable that holds a reference to the single created instance, if any.
o A public static means of getting the reference to the single created instance, creating one if necessary.

Example of how to write code with Singleton:


1. namespace Singleton {
2. class Program {
3. static void Main(string[] args) {
4. Calculate.Instance.ValueOne = 10.5;
5. Calculate.Instance.ValueTwo = 5.5;
6. Console.WriteLine("Addition : " + Calculate.Instance.Addition());
7. Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
8. Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
9. Console.WriteLine("Division : " + Calculate.Instance.Division());
10. Console.WriteLine("\n----------------------\n");
11. Calculate.Instance.ValueTwo = 10.5;
12. Console.WriteLine("Addition : " + Calculate.Instance.Addition());
13. Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
14. Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
15. Console.WriteLine("Division : " + Calculate.Instance.Division());
16. Console.ReadLine();
17. }
18. }
19. public sealed class Calculate {
20. private Calculate() {}
21. private static Calculate instance = null;
22. public static Calculate Instance {
23. get {
24. if (instance == null) {
25. instance = new Calculate();
26. }
27. return instance;
28. }
29. }
30. public double ValueOne {
31. get;
32. set;
33. }
34. public double ValueTwo {
35. get;
36. set;
37. }
38. public double Addition() {
39. return ValueOne + ValueTwo;
40. }
41. public double Subtraction() {
42. return ValueOne - ValueTwo;
43. }
44. public double Multiplication() {
45. return ValueOne * ValueTwo;
46. }
47. public double Division() {
48. return ValueOne / ValueTwo;
49. }
50. }
51. }
To read more about Singleton in depth so follow the link, Singleton Design Pattern in C#

29. Difference between Throw Exception and Throw Clause


The basic difference is that the Throw exception overwrites the stack trace. This makes it 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.

Let's see what it means to better understand the differences. I am using a console application to easily test and see how the usage of the two
differ in their functionality.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace TestingThrowExceptions {
6. class Program {
7. public void ExceptionMethod() {
8. throw new Exception("Original Exception occurred in ExceptionMethod");
9. }
10. static void Main(string[] args) {
11. Program p = new Program();
12. try {
13. p.ExceptionMethod();
14. } catch (Exception ex) {
15. throw ex;
16. }
17. }
18. }
19. }
Now run the code by pressing the F5 key and see what happens. It returns an exception and look at the stack trace.

To learn more about throw exceptions, please visit, Difference Between Throw Exception and Throw Clause

30. 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#. They are not an essential part of object-oriented programming.
Defining an indexer allows you to create classes that act as virtual arrays. Instances of that class can be accessed using the [] array access
operator.

Creating an Indexer

1. < modifier > <


2. return type > this[argument list] {
3. get {
4. // your get block code
5. }
6. set {
7. // your set block code
8. }
9. }
In the above code,

<modifier>

can be private, public, protected or internal.

<return type>

can be any valid C# types.

To learn more about indexers in C#, visit Indexers in C#.


31. What is a multicast delegate in C#?
Delegate is one of the base types in .NET. Delegate is a class that is used to create and invoke delegates at runtime.

A delegate in C# allows developers to treat methods as objects and invoke them from their code.

Implement Multicast Delegates Example:

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. delegate void MDelegate();
6. class DM {
7. static public void Display() {
8. Console.WriteLine("Meerut");
9. }
10. static public void print() {
11. Console.WriteLine("Roorkee");
12. }
13. }
14. class MTest {
15. public static void Main() {
16. MDelegate m1 = new MDelegate(DM.Display);
17. MDelegate m2 = new MDelegate(DM.print);
18. MDelegate m3 = m1 + m2;
19. MDelegate m4 = m2 + m1;
20. MDelegate m5 = m3 - m2;
21. m3();
22. m4();
23. m5();
24. }
25. }
Learn more about delegates in C# here, Delegates in C#.

32. Difference between the Equality Operator (==) and Equals() Method in C#
Both the == Operator and the Equals() method are used to 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. Let’s see with some examples.

In this example, we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is
assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True
output for both the == Operator and the Equals() method.

1. using System;
2. namespace ComparisionExample {
3. class Program {
4. static void Main(string[] args) {
5. string name = "sandeep";
6. string myName = name;
7. Console.WriteLine("== operator result is {0}", name == myName);
8. Console.WriteLine("Equals method result is {0}", name.Equals(myName));
9. Console.ReadKey();
10. }
11. }
12. }
For more details, check out the following link, Difference Between Equality Operator ( ==) and Equals() Method in C#.

33. What's the Difference between the Is and As operator 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.

Let's understand this in our C# code. We declare two classes, Speaker and Author.

1. class Speaker {
2. public string Name {
3. get;
4. set;
5. }
6. }
7. class Author {
8. public string Name {
9. get;
10. set;
11. }
12. }

Now, let's create an object of type Speaker:


1. var speaker = new Speaker { Name="Gaurav Kumar Arora"};
Now, let’s check if the object is Speaker type:

1. var isTrue = speaker is Speaker;


In the preceding, we are checking the matching type. Yes, our speaker is an object of Speaker type.

1. Console.WriteLine("speaker is of Speaker type:{0}", isTrue);


So, the results are true.

But, here we get false:

1. var author = new Author { Name = "Gaurav Kumar Arora" };


2. var isTrue = speaker is Author;
3. Console.WriteLine("speaker is of Author type:{0}", isTrue);
Because our speaker is not an object of Author type.

"as" operator

The "as" operator behaves in a similar way as the "is" operator. The only difference is it returns the object if both are compatible with that type.
Else it returns a null.

Let's understand this in our C# code.

1. public static string GetAuthorName(dynamic obj)


2. {
3. Author authorObj = obj as Author;
4. return (authorObj != null) ? authorObj.Name : string.Empty;
5. }
We have a method that accepts a dynamic object and returns the object name property if the object is of the Author type.

Here, we’ve declared two objects:


1. var speaker = new Speaker { Name="Gaurav Kumar Arora"};
2. var author = new Author { Name = "Gaurav Kumar Arora" };

The following returns the "Name" property:


1. var authorName = GetAuthorName(author);
2. Console.WriteLine("Author name is:{0}", authorName);

It returns an empty string:


1. authorName = GetAuthorName(speaker);
2. Console.WriteLine("Author name is:{0}", authorName);

Learn more about is vs as operators here, "is" and "as" Operators of C#

34. How to use Nullable<> Types in C#?


A nullable type is a data type is that contains the defined data type or the null value.

This nullable type concept is not compatible with "var".

Any data type can be declared nullable type with the help of operator "?".

For example, the following code declares the int 'i' as a null.

1. int? i = null;
As discussed in the previous section "var" is not compatible with nullable types. So, if you declare the following, you will get an error.

1. var? i = null;
To learn more about nullable types in C#, read the following, Getting started with Nullable Types in C#.
35. What are Different Ways a Method can be Overloaded?
Method overloading is a way to achieve compile-time polymorphism where we can use a method with the same name but different signatures.
For example, the following code example has a method volume with three different signatures based on the number and type of parameters
and return values.

Example

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace Hello_Word {
7. class overloding {
8. public static void Main() {
9. Console.WriteLine(volume(10));
10. Console.WriteLine(volume(2.5F, 8));
11. Console.WriteLine(volume(100L, 75, 15));
12. Console.ReadLine();
13. }
14.
15. static int volume(int x) {
16. return (x * x * x);
17. }
18.
19. static double volume(float r, int h) {
20. return (3.14 * r * r * h);
21. }
22.
23. static long volume(long l, int b, int h) {
24. return (l * b * h);
25. }
26. }
27. }
Note
If we have a method that has two parameter object type and has the same name method with two integer parameters, when we call that
method with int value, it will call that method with integer parameters instead of the object type parameters method.

Read the following article to learn more here, Method Overloading in C#.

36. What is an Object Pool in .Net?


Object Pooling in .NET allows objects to keep in the memory pool so the objects can be reused without recreating them. This article explains
what object pooling is in .NET and how to implement object pooling in C#.

What does it mean?

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 and it 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 give you back.

To learn more about object pooling in C# and .NET, read the following, Object Pooling in .NET.

37. What are Generics in C#?


Generics allow you to delay the specification of the data type of programming elements in a class or a method until it is actually used in the
program. In other words, generics allow you to write a class or method that can work with any data type.

You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor
for the class or a function call for the method, it generates code to handle the specific data type.

Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot. Generics are
most frequently used with collections and the methods that operate on them. Version 2.0 of the .NET Framework class library provides a new
namespace, System.Collections.Generic, that contains several new generic-based collection classes. It is recommended that all applications
that target the .NET Framework 2.0 and later use the new generic collection classes instead of the older non-generic counterparts such as
ArrayList.

Features of Generics

Generics are a technique that enriches your programs in the following ways:

 It helps you to maximize code reuse, type safety, and performance.


 You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the
System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the
System.Collections namespace.
 You can create your own generic interfaces, classes, methods, events, and delegates.
 You may create generic classes constrained to enable access to methods on specific data types.
 You may get information on the types used in a generic data type at run-time using reflection.

Learn more about generic classes in C# here, Using Generics In C#.

38. Describe Accessibility Modifiers in C#


Access modifiers are keywords used to specify the declared accessibility of a member or a type.

Access modifiers are keywords used to specify the scope of accessibility of a member of a type or the type itself. For example, a public class is
accessible to the entire world, while an internal class may be accessible to the assembly only.

Why use access modifiers?


Access modifiers are an integral part of object-oriented programming. Access modifiers are used to implement the encapsulation of OOP.
Access modifiers allow you to define who does or who doesn't have access to certain features.

In C# there are 6 different types of Access Modifiers:

Modifier Description

public There are no restrictions on accessing public members.

private Access is limited to within the class definition. This is the default access modifier type if none is formally specified

protected Access is limited to within the class definition and any class that inherits from the class

internal Access is limited exclusively to classes defined within the current project assembly

protected Access is limited to the current assembly and types derived from the containing class. All members in the current project and all
internal members in derived class can access the variables.

private
Access is limited to the containing class or types derived from the containing class within the current assembly.
protected

To learn more about access modifiers in C#, click here, What are Access Modifiers in C#?

39. What is a Virtual Method in C#?


A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as
derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A
virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the
virtual keyword and that method is overridden in the derived class using the override keyword.

When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the
derived class to override that method. The overriding method also provides more than one form for a method. Hence, it is also an example of
polymorphism.

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no
need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is
a need to override it in the derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most
derived class is called, which might be the original member if no derived class has overridden the member.

Virtual Method

1. By default, methods are non-virtual. We can't override a non-virtual method.


2. We can't use the virtual modifier with static, abstract, private or override modifiers.

Learn more about virtual methods in C# here, Virtual Method in C#.

40. What is the Difference between an Array and ArrayList in C#?


Here is a list of differences between the two:
To learn more about arrays, collections, and ArrayLists, click here, Collections in C#: ArrayList and Arrays.

41. What are Value types and Reference types in C#?


In C#, data types can be of two types, value types, and reference types. Value type variables contain their object (or data) directly. If we copy
one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will independently
operate on their values, Value type data types are stored on a stack and reference data types are stored on a heap.

In C#, basic data types include int, char, bool, and long, which are value types. Classes and collections are reference types.

For more details, follow this link, C# Concepts: Value Type and Reference Type
42. What is Serialization in C#?
Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main
purpose is to save the state of an object in order to be 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).

Learn more about serialization in C# here, Serializing Objects in C#

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

Learn more here, The "Using" Statement in C#

44. 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."

A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.

Example

1. int[][] jagArray = new int[5][];


In the above declaration, the rows are fixed in size. But columns are not specified as they can vary.

Declaring and initializing a jagged array.

1. int[][] jaggedArray = new int[5][];


2. jaggedArray[0] = new int[3];
3. jaggedArray[1] = new int[5];
4. jaggedArray[2] = new int[2];
5. jaggedArray[3] = new int[8];
6. jaggedArray[4] = new int[10];
7. jaggedArray[0] = new int[] { 3, 5, 7, };
8. jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
9. jaggedArray[2] = new int[] { 1, 6 };
10. jaggedArray[3] = new int[] { 1, 0, 2, 4, 6, 45, 67, 78 };
11. jaggedArray[4] = new int[] { 1, 0, 2, 4, 6, 34, 54, 67, 87, 78 };
Learn more here, Jagged Array in C#

45. What is Multithreading with .NET?


Multithreading allows a program to run multiple threads concurrently. This article explains how multithreading works in .NET. This article covers
the entire range of threading areas from thread creation, race conditions, deadlocks, monitors, mutexes, synchronization and semaphores and
so on.

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 to be a lightweight process
because it runs within the context of a program and takes advantage of the resources allocated for that program.

A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.

To learn more about threading in .NET, visit, Multithreading with .NET

46. 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, 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 by using “new” keyword together with the object initializer.

Example

1. var anonymousData = new


2. {
3. ForeName = "Jignesh",
4. SurName = "Trivedi"
5. };
6. Console.WriteLine("First Name : " + anonymousData.ForeName);

Anonymous Types with LINQ Example

Anonymous types are also used with the "Select" clause of LINQ query expression to return a subset of properties.

Example

If any object collection has properties calling FirstName, LastName, DOB, etc... and you want only FirstName and LastName after the Querying
the data, then:

1. class MyData {
2. public string FirstName {
3. get;
4. set;
5. }
6. public string LastName {
7. get;
8. set;
9. }
10. public DateTime DOB {
11. get;
12. set;
13. }
14. public string MiddleName {
15. get;
16. set;
17. }
18. }
19. static void Main(string[] args) {
20. // Create Dummy Data to fill Collection.
21. List < MyData > data = new List < MyData > ();
22. data.Add(new MyData {
23. FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(
1990, 12, 30)
24. });
25. data.Add(new MyData {
26. FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6
)
27. });
28. data.Add(new MyData {
29. FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1
993, 10, 8)
30. });
31. data.Add(new MyData {
32. FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = newDateTime(1983, 6, 15)
33. });
34. data.Add(new MyData {
35. FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1988
, 7, 20)
36. });
37. }
38. var anonymousData = from pl in data
39. select new {
40. pl.FirstName, pl.LastName
41. };
42. foreach(var m in anonymousData) {
43. Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);
44. }
45. }
47. What is a Hashtable in C#?
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot
have duplicate entries in a Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to
implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the
collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are
added to a hash table, a hash code is generated automatically. This code is hidden from the developer. Access to the table's values is
achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be
considered to be randomly ordered.

The Hashtable Collection

The Base Class libraries offer a Hashtable Class that is defined in the System.Collections namespace, so you don't have to code your own
hash tables. It processes each key of the hash that you add every time and then uses the hash code to look up the element very quickly. The
capacity of a hash table is the number of elements the hash table can hold. As elements are added to a hash table, the capacity is
automatically increased as required through reallocation. It is an older .Net Framework type.

Declaring a Hashtable

The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the examples, we have to add using
System.Collections; to the source code. The declaration for the Hashtable is:

1. Hashtable HT = new Hashtable ();


48. What is LINQ in C#?
LINQ stands for Language Integrated Query. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a
syntax similar to a SQL query.
LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can
easily retrieve data from any object that implements the IEnumerable<T> interface.

Advantages of LINQ

1. LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ, we
can query a database and XML as well as collections.
2. Compile-time syntax checking.

It allows you to query collections like arrays, enumerable classes, etc... in the native language of your application, like in VB or C# in much the
same way you would query a database using SQL.
49. What is File Handling in C#.Net?
The System.IO namespace provides four classes that allow you to manipulate individual files, as well as interact with a machine directory
structure. The Directory and File directly extend System.Object and supports the creation, copying, moving and deletion of files using various
static methods. They only contain static methods and are never instantiated. The FileInfo and DirecotryInfo types are derived from the abstract
class FileSystemInfo type and they are typically employed for obtaining the full details of a file or directory because their members tend to
return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are stateful and members of
these classes are not static.

For more details follow the links, File Handling in C# .NET


50. What is Reflection in C#?
Reflection is the process of runtime type discovery to inspect metadata, CIL code, late binding, and self-generating code. At the run time by
using reflection, we can access the same "type" information as displayed by the ildasm utility at design time. The reflection is analogous to
reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including
methods, fields, events, and properties.

You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace.

Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera. Reflection is also
used in the external disassembling tools such as Reflector, Fxcop, and NUnit because .NET tools don't need to parse the source code similar
to C++.

Metadata Investigation

The following program depicts the process of reflection by creating a console-based application. This program will display the details of the
fields, methods, properties, and interfaces for any type within the mscorlib.dll assembly. Before proceeding, it is mandatory to import
"System.Reflection".

Here, we are defining a number of static methods in the program class to enumerate fields, methods, and interfaces in the specified type. The
static method takes a single "System.Type" parameter and returns void.

1. static void FieldInvestigation(Type t) {


2. Console.WriteLine("*********Fields*********");
3. FieldInfo[] fld = t.GetFields();
4. foreach(FieldInfo f in fld) {
5. Console.WriteLine("-->{0}", f.Name);
6. }
7. }
8.
9. static void MethodInvestigation(Type t) {
10. Console.WriteLine("*********Methods*********");
11. MethodInfo[] mth = t.GetMethods();
12. foreach(MethodInfo m in mth) {
13. Console.WriteLine("-->{0}", m.Name);
14. }
15. }
https://www.mytectra.com/interview-question/c-interview-questions-and-answers-for-5-years-experienced

Q1. What is C-Sharp (C#)?


Ans: C# is a type-safe, managed and object oriented language, which is compiled by .Net framework for generating intermediate
language (IL).

Q2. Explain the types of comments in C#?


Ans: Below are the types of comments in C#:

Single Line Comment Eg : //

Multiline Comments Eg: /* */

XML Comments Eg : ///


Q3. So what makes your code really object-oriented?
Ans: In order to understand this, we must first analyze what benefits we can derive from OO. In order to do this, we must clearly
understand its foundation. So given that C# is at its core object-oriented.

Q4. What is Cohesion?


Ans: In OOPS we develop our code in modules. Each module has certain responsibilities. Cohesion shows how much a module
responsibilities are strongly related.

Higher cohesion is always preferred. Higher cohesion benefits are:

 Improves maintenance of modules.


 Increase reusability.

Q5. Why are strings in C# immutable?


Ans: Immutable means string values cannot be changed once they have been created. Any modification to a string value results in
a completely new string instance, thus an inefficient use of memory and extraneous garbage collection. The mutable
System.Text.StringBuilder class should be used when string values will change.

Q6. List out the differences between Array and Array List in C#?
Ans: Array stores the values or elements of same data type but array list stores values of different data types.

Arrays will use the fixed length but array list does not uses fixed length like array.

Q7. What are the fundamental principles of OO programming?


Ans: As a developer, you might be tempted to answer that it comprises things like Encapsulation, Polymorphism, Abstraction, and
Inheritance. Although this is true, it doesn’t really explain the fundamental core of what OO is and what its benefits are.

Principles are crucial but they are not the most important aspect of what OO actually is. What is really important is to understand in
what grounds OO is built upon, or in other words, what are the foundations of OO programming.

The two most fundamental core concepts on which OO has been built upon in C# are this pointer and Dynamic Dispatch.

Obviously, there are principles like Encapsulation, Polymorphism, Abstraction, and Inheritance, but these are the consequence and
not the generating force behind the OO paradigm in C#.

Q8. What is coupling?


Ans: OOPS Modules are dependent on each other. Coupling refers to level of dependency between two software modules.

Two modules are highly dependent on each other if you have changed in one module and for supporting that change every time
you have to change in dependent module.

Loose Coupling is always preferred.

Inversion of Control and dependency injections are some techniques for getting loose coupling in modules.

Q9. What is the execution entry point for a C# console application?


Ans: The Main method.

Q10. Why to use “using” in C#?


Ans: “Using” statement calls – “dispose” method internally, whenever any exception occurred in any method call and in “Using”
statement objects are read only and cannot be reassignable or modifiable.

Q11. What is the this Pointer?


Ans: The this pointer is silently passed with a call to an instance-level function, which then operates on an object (instance of a
class).

Basically, this core mechanism makes it possible to bring operations close to data. It also eliminates the need to have global
functions and it gives data structures the intrinsic ability to perform operations on its data.

Q12. What is Abstraction?


Ans: Abstraction is a technique of taking something specific and making it less specific.

In OOPS we achieve the abstraction by separating the implementation from interface. We take a implemented class and took only
those method signatures and properties which are required by the class client. We put these method signatures and properties into
interface or abstract class.

Q13. How do you initiate a string without escaping each backslash?


Ans: You put an @ sign in front of the double-quoted string.

String ex = @"This has a carriage return\r\n"

Q14. Explain namespaces in C#?


Ans: Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword
can be used for using the namespace in other namespace.

Q15. What is the OO fundamental idea using C# that allows a data structure to perform operations on its own
data?
Ans: What would your answer be? Pretty obvious. The humble this pointer.

Notice that despite this being a mind-bending idea, we can already start to appreciate the bigger picture for which C# was
designed.

The this pointer is basically a way for a data structure (object) to be able to access methods that allow itself to perform operations
on its own data. It is a way to manage state within a data structure.

Now let’s talk a bit about the other core concept that takes this to the next level.

Q16. What is Encapsulation?


Ans: In non object oriented languages, data and behaviors are not tied together. That means any function in the program can
modify the data.

In Encapsulation, we bind the data and behaviors in one object. Only defined behaviors in a class can modify the data. We hide the
state of an object by using properties and methods. Clients of the object only see these behaviors and by only these behaviors
clients can modify the data.

We also protect the data by using access specifiers. We put the private / protected keywords before data to protect it from the
outside world.
Q17. What is the difference between a struct and a class?
Ans: Structs cannot be inherited. Structs are passed by value and not by reference. Structs are stored on the stack not the heap.
The result is better performance with Structs.

Q18. Explain “static” keyword in C#?


Ans: “Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are
also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.

Q19. What is a singleton?


Ans: A singleton is a design pattern used when only one instance of an object is created and shared; that is, it only allows one
instance of itself to be created. Any attempt to create another instance simply returns a reference to the first one. Singleton classes
are created by defining all class constructors as private. In addition, a private static member is created as the same type of the
class, along with a public static member that returns an instance of the class. Here is a basic example:

public class SingletonExample { private static SingletonExample _Instance; private SingletonExample () { } public static
SingletonExample Get Instance() { if (_Instance == null) { _Instance = new SingletonExample (); } return _Instance; }}

Q20. Why to use “finally” block in C#?


Ans: “Finally” block will be executed irrespective of exception. So while executing the code in try block when exception is occurred,
control is returned to catch block and at last “finally” block will be executed. So closing connection to database / releasing the file
handlers can be kept in “finally” block.

Q21. What is boxing?


Ans: Boxing is the process of explicitly converting a value type into a corresponding reference type. Basically, this involves creating
a new object on the heap and placing the value there. Reversing the process is just as easy with unboxing, which converts the
value in an object reference on the heap into a corresponding value type on the stack. The unboxing process begins by verifying
that the recipient value type is equivalent to the boxed type. If the operation is permitted, the value is copied to the stack

Q22. Can we have only “try” block without “catch” block in C#?
Ans: Yes we can have only try block without catch block.

Q23. How to move to a State-related Codebase?


Ans: So now that we’ve explored these concepts, let’s move to a state-related code base. So you might be asking yourself at this
moment.

Q24. What is the difference between “out” and “ref” parameters in C#?
Ans: “out” parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before
it is used.

Q25. How are methods overloaded?


Ans: Methods are overloaded via different signatures (number of parameters and types). Thus, you can overload a method by
having different data types, different number of parameters, or a different order of parameters.

Q26. Explain Jagged Arrays in C#?


Ans: If the elements of an array is an array then it’s called as jagged array. The elements can be of different sizes and dimensions.

Q27. How do you prevent a class from being inherited?


Ans: The sealed keyword prohibits a class from being inherited.

Q28. What you mean by inner exception in C#?


Ans: Inner exception is a property of exception class which will give you a brief insight of the exception i.e, parent exception and
child exception details.

Q29. What is the GAC, and where is it located?


Ans: The GAC is the Global Assembly Cache. Shared assemblies reside in the GAC; this allows applications to share assemblies
instead of having the assembly distributed with each application. Versioning allows multiple assembly versions to exist in the GAC
—applications can specify version numbers in the config file. The gacutil command line tool is used to manage the GAC.

Q30. Explain circular reference in C#?


Ans: This is a situation where in, multiple resources are dependent on each other and this causes a lock condition and this makes
the resource to be unused.

https://www.toptal.com/c-sharp/interview-questions

Given an array of ints, write a C# method to total all the values that are even numbers.
Hide answer
There are of course many ways to do this, but two of the most straightforward would be either:

static long TotalAllEvenNumbers(int[] intArray) {


return intArray.Where(i => i % 2 == 0).Sum(i => (long)i);
}

or:

static long TotalAllEvenNumbers(int[] intArray) {


return (from i in intArray where i % 2 == 0 select (long)i).Sum();
}

Here are the key things to look for in the answer:

1. Does the candidate take advantage of the C# language constructs which make a one-liner solution possible (i.e., rather than employing a
more lengthy solution which contains a loop, conditional statement, and accumulator)?

2. Does the candidate consider the possibility of overflow. For example, an implementation such as return intArray.Where(i => i % 2
== 0).Sum() (regardless of the return type of the function) might be an “obvious” one-line solution, but the probability of overflow here is
high. While the approach used in the answers above of converting to long doesn’t eliminate the possibility, it makes it a highly unlikely
that an overflow exception will occur. Note that, if the candidate asks about the expected size of the array and the magnitude of its
members, he or she is obviously considering this overflow issue, which is part of what we’re looking to ascertain.
What is the output of the short program below? Explain your answer.
class Program {
static String location;
static DateTime time;

static void Main() {


Console.WriteLine(location == null ? "location is null" : location);
Console.WriteLine(time == null ? "time is null" : time.ToString());
}
}
Hide answer

The output will be:

location is null
1/1/0001 12:00:00 AM
Although both variables are uninitialized, String is a reference type and DateTime is a value type. As a value type, an
unitialized DateTime variable is set to a default value of midnight of 1/1/1 (yup, that’s the year 1 A.D.), not null .
Is the comparison of time and null in the if statement below valid or not? Why or
why not?
static DateTime time;
/* ... */
if (time == null)
{
/* do something */
}
Hide answer

One might think that, since a DateTime variable can never be null (it is automatically initialized to Jan 1, 0001), the compiler would
complain when a DateTime variable is compared to null . However, due to type coercion, the compiler does allow it, which can
potentially lead to headfakes and pull-out-your-hair bugs.
Specifically, the == operator will cast its operands to different allowable types in order to get a common type on both sides, which it
can then compare. That is why something like this will give you the result you expect (as opposed to failing or behaving
unexpectedly because the operands are of different types):
double x = 5.0;
int y = 5;
Console.WriteLine(x == y); // outputs true
However, this can sometimes result in unexpected behavior, as is the case with the comparison of a DateTime variable and null .
In such a case, both the DateTime variable and the null literal can be cast to Nullable<DateTime> . Therefore it is legal to compare
the two values, even though the result will always be false.
Apply to Join Toptal's Developer Network and enjoy reliable, steady, remote freelance C# jobs.
APPLY TO TOPTAL'S FREELANCE C# JOBS

Given an instance circle of the following class:


public sealed class Circle {
private double radius;

public double Calculate(Func<double, double> op) {


return op(radius);
}
}

write code to calculate the circumference of the circle, without modifying


the Circle class itself.
Hide answer

The preferred answer would be of the form:

circle.Calculate(r => 2 * Math.PI * r);


Since we don’t have access to the private radius field of the object, we tell the object itself to calculate the circumference, by
passing it the calculation function inline.
A lot of C# programmers shy away from (or don’t understand) function-valued parameters. While in this case the example is a little
contrived, the purpose is to see if the applicant understands how to formulate a call to Calculate which matches the method’s
definition.
Alternatively, a valid (though less elegant) solution would be to retrieve the radius value itself from the object and then perform the
calculation with the result:

var radius = circle.Calculate(r => r);


var circumference = 2 * Math.PI * radius;
Either way works. The main thing we’re looking for here is to see that the candidate is familiar with, and understands how to invoke,
the Calculate method.

What is the output of the program below? Explain your answer.


class Program {
private static string result;

static void Main() {


SaySomething();
Console.WriteLine(result);
}

static async Task<string> SaySomething() {


await Task.Delay(5);
result = "Hello world!";
return “Something”;
}
}
Also, would the answer change if we were to replace await
Task.Delay(5); with Thread.Sleep(5) ? Why or why not?
Hide answer

The answer to the first part of the question (i.e., the version of the code with await Task.Delay(5); ) is that the program will just
output a blank line (not “Hello world!”). This is because result will still be uninitialized when Console.WriteLine is called.
Most procedural and object-oriented programmers expect a function to execute from beginning to end, or to a return statement,
before returning to the calling function. This is not the case with C# async functions. They only execute up until the
first await statement, then return to the caller. The function called by await (in this case Task.Delay ) is executed asynchronously,
and the line after the await statement isn’t signaled to execute until Task.Delay completes (in 5 milliseconds). However, within that
time, control has already returned to the caller, which executes the Console.WriteLine statement on a string that hasn’t yet been
initialized.
Calling await Task.Delay(5) lets the current thread continue what it is doing, and if it’s done (pending any awaits), returns it to the
thread pool. This is the primary benefit of the async/await mechanism. It allows the CLR to service more requests with less threads
in the thread pool.
Asynchronous programming has become a lot more common, with the prevalence of devices which perform over-the-network
service requests or database requests for many activities. C# has some excellent programming constructs which greatly ease the
task of programming asynchronous methods, and a programmer who is aware of them will produce better programs.
With regard to the second part of the question, if await Task.Delay(5); was replaced with Thread.Sleep(5) , the program would
output Hello world! . An async method without at least one await statement in it operates just like a synchronous method; that is,
it will execute from beginning to end, or until it encounters a return statement. Calling Thread.Sleep() simply blocks the currently
running thread, so the Thread.Sleep(5) call just adds 5 milliseconds to the execution time of the SaySomething() method.

What is the output of the program below? Explain your answer.


delegate void Printer() ;

static void Main()


{
List<Printer> printers = new List<Printer>();
int i= 0 ;
for (; i < 10 ; i++)
{
printers.Add( delegate { Console.WriteLine(i); });
}

foreach ( var printer in printers)


{
printer();
}
}
Hide answer

This program will output the number 10 ten times.

Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i is
stored, rather than the value itself. Therefore, after we exit the loop, the variable i has been set to 10, so by the time each
delegate is invoked, the value passed to all of them is 10.

It is possible to store mixed datatypes such as int, string, float, char all in one array?
Hide answer
Yes! It is possible to do so because the array can be of type object that can not only store any datatype but also the object of the
class as shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication8
{

class Program
{

class Customer
{
public int ID { get ; set ; }
public string Name { get ; set ; }

public override string ToString()


{
return this .Name;
}
}

static void Main(string[] args)


{
object [] array = new object [ 3 ];
array[ 0 ] = 101 ;
array[ 1 ] = "C#" ;
Customer c = new Customer();
c.ID = 55 ;
c.Name = "Manish" ;
array[ 2 ] = c;
foreach ( object obj in array)
{
Console.WriteLine(obj);
}
Console.ReadLine();
}
}
}
Compare structs and classes in C#. What do they have in common? How do they
differ?
Hide answer

Classes and Structs in C# do have a few things in common, namely:


 Are compound data types

 Can contain methods and events

 Can support interfaces

But there are a number of differences. Here’s a comparison:


Classes:
 Support inheritance

 Are reference (pointer) types

 The reference can be null

 Have memory overhead per new instance

Structs:
 Do not support inheritance
 Are value types

 Are passed by value (like integers)

 Cannot have a null reference (unless Nullable is used)

 Do not have memory overhead per new instance (unless “boxed”)

You’re given a word string containing at least one $ symbol, e.g.:


"foo bar foo $ bar $ foo bar $ "
Question: How do you remove all but the first occurrence of $ from a given string?
Hide answer

This problem has two parts: Preserving the first occurrence and replacing all the others.
We can solve it using a regular expression and String.Replace() :
using System;
using System.Text.RegularExpressions;

class MainClass {
public static void Main (string[] args) {
string s = "like for example $ you don't have $ network $ access" ;
Console.WriteLine( "before: {0}" , s);

GroupCollection halves = Regex.Match(s, @"([^$]*\$)(.*)" ).Groups;


string answer = halves[ 1 ].Value + halves[ 2 ].Value.Replace( "$" , "" );

Console.WriteLine( "after: {0}" , answer);

// like for example $ you don't have network access


}
}

Explanation:

 ([^$]*\$) —Group 1 captures any number of non- $ characters, plus a single $ character (escaped with a \ )
 (.*) —Group 2 (greedily) captures everything else
With the first occurrence of $ preserved in halves[1].Value , we can simply use String.Replace() on halves[2].Value to
eliminate all $ characters found in the remainder of the string, without the need for a second regular expression.
What is the output of the program below?
public class TestStatic
{
public static int TestValue;

public TestStatic()
{
if (TestValue == 0 )
{
TestValue = 5 ;
}
}

static TestStatic()
{
if (TestValue == 0 )
{
TestValue = 10 ;
}

public void Print()


{
if (TestValue == 5 )
{
TestValue = 6 ;
}
Console.WriteLine( "TestValue : " + TestValue);

}
}

public void Main(string[] args)


{

TestStatic t = new TestStatic();


t.Print();
}
Hide answer
TestValue : 10

The static constructor of a class is called before any instance of the class is created. The static constructor called here initializes
the TestValue variable first.

class ClassA
{
public ClassA() { }

public ClassA(int pValue) { }


}

At the client side:


class Program
{
static void Main(string[] args)
{
ClassA refA = new ClassA();
}
}

Question:
Is there a way to modify ClassA so that you can you call the constructor with
parameters, when the Main method is called, without creating any other new instances
of the ClassA ?
Hide answer

The this keyword is used to call other constructors, to initialize the class object. The following shows the implementation:
class ClassA
{

public ClassA() : this(10)


{ }

public ClassA(int pValue)


{ }
}

What does the following code output?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace main1
{

class Program
{

static void Main(string[] args)


{

try
{
Console.WriteLine( "Hello" );
}
catch (ArgumentNullException)
{
Console.WriteLine( "A" );
}
catch (Exception)
{
Console.WriteLine( "B" );
}

finally
{
Console.WriteLine( "C" );
}
Console.ReadKey();
}
}
}
Hide answer

Hello
C

Describe dependency injection.


Hide answer

Dependency injection is a way to de-couple tightly linked classes, thereby reducing the direct dependency of classes upon each
other. There are different ways by which dependency injection can be achived:

1. Constructor dependency

2. Property dependency

3. Method dependency
Write a C# program that accepts a distance in kilometers, converts it into meters, and
then displays the result.
Hide answer

using system;

class abc
{

public static Void Main()


{
int ndistance, nresult;
Console.WriteLine( "Enter the distance in kilometers" );
ndistance = convert.ToInt32(Console.ReadLine());
nresult = ndistance * 1000 ;
Console.WriteLine( "Distance in meters: " + nresult);
Console.ReadLine();
}
}

Describe boxing and unboxing. Provide an example.


Hide answer

Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by the value type. Boxing a
value type creates an object instance containing the value and stores it on the heap.
Example:

int x = 101;
object o = x; // boxing value of x into object o
o = 999;
x = (int)o; // unboxing value of o into integer x

https://www.softwaretestinghelp.com/c-sharp-interview-questions/

Frequently asked basic C# Interview Questions on Programming and Coding:


C# is a programming language that has grown rapidly and is also used widely. It is in high demand, versatile and supports cross-platform
as well.

It is not just used for windows but many other operating systems. Hence, it is very important to have a strong understanding of this
language to land in any job in the Software Testing industry.

Below enlisted are not just a set of most frequently asked questions of C# but also some very important topics to be understood to stand
out from the crowd of the C# population.
What is System Testing

As C# is a vast topic, for the ease of addressing all the concepts, I have divided this topic into three parts as mentioned below:
 Questions on Basic Concepts
 Questions on Arrays and Strings
 Advanced Concepts
This article includes a set of top 50 C# interview questions and answers covering almost all its important topics in simple
terms, in order to help you prepare for your interview.
What You Will Learn: [show]
Most Popular C# Interview Questions And Answers
Basic Concepts
Q #1) What is an Object and a Class?
Answer: Class is an encapsulation of properties and methods that are used to represent a real-time entity. It is a data structure that
brings all the instances together in a single unit.
Object is defined as an instance of a Class. Technically, it is just a block of memory allocated that can be stored in the form of variables,
array or a collection.

Q #2) What are the fundamental OOP concepts?


Answer: The four fundamental concepts of Object-Oriented Programming are:
 Encapsulation: Here, the internal representation of an object is hidden from the view outside the object’s definition. Only the
required information can be accessed whereas the rest of the data implementation is hidden.
 Abstraction: It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
 Inheritance: It is the ability to create new classes from another class. It is done by accessing, modifying and extending the
behavior of objects in the parent class.
 Polymorphism: The name means, one name, many forms. It is achieved by having multiple methods with the same name but
different implementations.
Q #3) What is Managed and Unmanaged code?
Answer: Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code is based on .Net
platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused
memory.
Unmanaged code is any code that is executed by application runtime of any other framework apart from .Net. The application runtime will
take care of memory, security and other performance operations.

Q #4) What is an Interface?


Answer: Interface is a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.
Q #5) What are the different types of classes in C#?
Answer: The different types of class in C# are:
 Partial class: It allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
 Sealed class: It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the
class. It is denoted by the keyword Sealed.
 Abstract class: It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one
method. It is denoted by the keyword abstract.
 Static class: It is a class that does not allow inheritance. The members of the class are also static. It is denoted by the
keyword static. This keyword tells the compiler to check for any accidental instances of the static class.
Q #6) Explain code compilation in C#.
Answer: Code compilation in C# includes the following four steps:
 Compiling the source code into Managed code by C# compiler.
 Combining the newly created code into assemblies.
 Loading the Common Language Runtime(CLR).
 Executing the assembly by CLR.
Q #7) What are the differences between a Class and a Struct?
Answer: Given below are the differences between a Class and a Struct:
Class Struct

Supports Inheritance Does not support Inheritance

Class is Pass by reference (reference type) Struct is Pass by Copy (Value type)

Members are private by default Members are public by default

Good for larger complex objects Good for Small isolated models

Can use waste collector for memory management Cannot use Garbage collector and hence no Memory management

Q #8) What is the difference between the Virtual method and the Abstract method?
Answer: The Virtual method must always have a default implementation. However, it can be overridden in the derived class, although it
is not mandatory. It can be overridden using the override keyword.
An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements
the abstract method. An override keyword is not necessary here though it can be used.
Q #9) Explain Namespaces in C#.
Answer: They are used to organize large code projects. “System” is the most widely used namespace in C#. We can create our own
namespace and can also use one namespace in another, which is called Nested Namespaces.
They are denoted by the keyword “namespace”.

Q #10) What is “using” statement in C#?


Answer: “Using” keyword denotes that the particular namespace is being used by the program.
For Example, using System
Here, System is a namespace. The class Console is defined under System. So, we can use the console.writeline (“….”) or readline in
our program.
Q #11) Explain Abstraction.
Answer: Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hide unnecessary
information.
Let us take an example of a Car:
A driver of the car should know the details about the Car such as color, name, mirror, steering, gear, brake, etc. What he doesn’t have to
know is an internal engine, exhaust system.

So, Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal
information can be achieved by declaring such parameters as Private using the private keyword.
Q #12) Explain Polymorphism?
Answer: Programmatically, Polymorphism means the same method but different implementations. It is of 2 types, Compile-time and
Runtime.
 Compile-time polymorphism is achieved by operator overloading.
 Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime polymorphism.
For Example, If a class has a method Void Add(), polymorphism is achieved by overloading the method, that is, void Add(int a, int b),
void Add(int add) are all overloaded methods.
Q #13) How is Exception Handling implemented in C#?
Answer: Exception handling is done using four keywords in C#:
 try: Contains a block of code for which an exception will be checked.
 catch: It is a program that catches an exception with the help of the exception handler.
 finally: It is a block of code written to execute regardless of whether an exception is caught or not.
 Throw: Throws an exception when a problem occurs.
Q #14) What are C# I/O classes? What are the commonly used I/O classes?
Answer: C# has System.IO namespace, consisting of classes that are used to perform various operations on files like creating, deleting,
opening, closing, etc.
Some commonly used I/O classes are:
 File – Helps in manipulating a file.
 StreamWriter – Used for writing characters to a stream.
 StreamReader – Used for reading characters to a stream.
 StringWriter – Used for reading a string buffer.
 StringReader – Used for writing a string buffer.
 Path – Used for performing operations related to the path information.
Q #15) What is StreamReader/StreamWriter class?
Answer: StreamReader and StreamWriter are classes of namespace System.IO. They are used when we want to read or write
charact90, Reader-based data, respectively.
Some of the members of StreamReader are: Close(), Read(), Readline().
Members of StreamWriter are: Close(), Write(), Writeline().
Class Program1

using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)

//----------------code to read-------------------//

using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))

//-------------code to write-------------------//

}
}

Q #16) What is a Destructor in C#?


Answer: Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own.
System.GC.Collect() is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.
For Example:
~Car()

Console.writeline(“….”);

Q #17) What is an Abstract Class?


Answer: An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. This class should
always be inherited. An instance of the class itself cannot be created. If we do not want any program to create an object of a class, then
such classes can be made abstract.
Any method in the abstract class does not have implementations in the same class. But they must be implemented in the child class.

For Example:
abstract class AB1

Public void Add();

Class childClass : AB1

childClass cs = new childClass ();


int Sum = cs.Add();

All the methods in an abstract class are implicitly virtual methods. Hence, the virtual keyword should not be used with any methods in the
abstract class.

Q #18) What are Boxing and Unboxing?


Answer: Converting a value type to reference type is called Boxing.
For Example:
int Value1 -= 10;
//————Boxing——————//
object boxedValue = Value1;

Explicit conversion of same reference type (created by boxing) back to value type is called Unboxing.
For Example:
//————UnBoxing——————//
int UnBoxing = int (boxedValue);
Q #19) What is the difference between Continue and Break Statement?
Answer: Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of
the program to exit only the current iteration. It does not break the loop.

What is the difference between finally and finalize block?


Answer: finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an
exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.
finalize method is called just before garbage collection. It is used to perform clean up operations of Unmanaged code. It is automatically
called when a given instance is not subsequently called.

Arrays And Strings


Q #21) What is an Array? Give the syntax for a single and multi-dimensional array?
Answer: An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory
location.
For Example:
double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};

A single dimensional array is a linear array where the variables are stored in a single row. Above example is a single dimensional array.
Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example, int[,] numbers = new int[3,2] { {1,2} ,{2,3},{3,4} };


Q #22) What is a Jagged Array?
Answer: A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple
dimensions.
int[] jaggedArray = new int[4][];

Q #23) Name some properties of Array.


Answer: Properties of an Array include:
 Length: Gets the total number of elements in an array.
 IsFixedSize: Tells whether the array is fixed in size or not.
 IsReadOnly: Tells whether the array is read-only or not.
Q #24) What is an Array Class?
Answer: An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace system.
Q #25) What is a String? What are the properties of a String Class?
Answer: A String is a collection of char objects. We can also declare string variables in c#.
string name = “C# Questions”;
A string class in C# represents a string. The properties of the string class are:

 Chars get the Char object in the current String.


 Length gets the number of objects in the current String.
Q #26) What is an Escape Sequence? Name some String escape sequences in C#.
Answer: An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be
interpreted literally or it is a special character. An escape sequence is considered as a single character.
String escape sequences are as follows:
 \n – Newline character
 \b – Backspace
 \\ – Backslash
 \’ – Single quote
 \’’ – Double Quote
Q #27) What are Regular expressions? Search a string using regular expressions?
Answer: Regular expression is a template to match a set of input. The pattern can consist of operators, constructs or character literals.
Regex is used for string parsing and replacing the character string.
For Example:
* matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab and so on.

Searching a string using Regex:


static void Main(string[] args)

string[] languages = { "C#", "Python", "Java" };

foreach(string s in languages)

if(System.Text.RegularExpressions.Regex.IsMatch(s,"Python"))

Console.WriteLine("Match found");

The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch which returns true in
case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.

Q #28) What are the basic String Operations? Explain.


Answer: Some of the basic string operations are:
 Concatenate: Two strings can be concatenated either by using a System.String.Concat or by using + operator.
 Modify: Replace(a,b) is used to replace a string with another string. Trim() is used to trim the string at the end or at the beginning.
 Compare: System.StringComparison() is used to compare two strings, either a case-sensitive comparison or not case sensitive.
Mainly takes two parameters, original string, and string to be compared with.
 Search: StartWith, EndsWith methods are used to search a particular string.
Q #29) What is Parsing? How to Parse a Date Time String?
Answer: Parsing converts a string into another data type.
For Example:
string text = “500”;
int num = int.Parse(text);
500 is an integer. So, the Parse method converts the string 500 into its own base type, i.e int.
Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);
Advanced Concepts
Q #30) What is a Delegate? Explain.
Answer: A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are
derived from System.Delegate namespace. Both Delegate and the method that it refers to can have the same signature.
 Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created by the delegate using the new keyword.

AddNumbers an1 = new AddNumbers(number);


The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

public delegate int myDel(int number);

public class Program

public int AddNumbers(int a)

int Sum = a + 10;


return Sum;

public void Start()

myDel DelgateExample = AddNumbers;

In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the
same signature as the delegate, called AddNumbers().

If there is another method called Start() which creates an object of the delegate, then the object can be assigned to AddNumbers as it
has the same signature as that of the delegate.

Q #31) What are Events?


Answer: Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse
movements, keypress and so on.
Programmatically, a class that raises an event is called a publisher and a class which responds/receives the event is called a subscriber.
Event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events.

Public delegate void PrintNumbers();


Event PrintNumbers myEvent;
Q #32) How to use Delegates with Events?
Answer: Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are
declared.
Let us see an example:
Consider a class called Patient. Consider two other classes, Insurance, and Bank which requires Death information of the Patient from
patient class. Here, Insurance and Bank are the subscribers and the Patient class becomes the Publisher. It triggers the death event and
the other two classes should receive the event.

namespace ConsoleApp2

public class Patient

public delegate void deathInfo();//Declaring a Delegate//

public event deathInfo deathDate;//Declaring the event//

public void Death()

deathDate();

public class Insurance

Patient myPat = new Patient();

void GetDeathDetails()

//-------Do Something with the deathDate event------------//

void Main()
{

//--------Subscribe the function GetDeathDetails----------//

myPat.deathDate += GetDeathDetails;

public class Bank

Patient myPat = new Patient();

void GetPatInfo ()

//-------Do Something with the deathDate event------------//

void Main()

//--------Subscribe the function GetPatInfo ----------//

myPat.deathDate += GetPatInfo;

Q #33) What are the different types of Delegates?


Answer: Different types of Delegates are:
 Single Delegate: A delegate that can call a single method.
 Multicast Delegate: A delegate that can call multiple methods. + and – operators are used to subscribe and unsubscribe
respectively.
 Generic Delegate: It does not require an instance of the delegate to be defined. It is of three types, Action, Funcs and Predicate.
 Action– In the above example of delegates and events, we can replace the definition of delegate and event using Action
keyword. The Action delegate defines a method that can be called on arguments but does not return a result
Public delegate void deathInfo();
Public event deathInfo deathDate;
//Replacing with Action//
Public event Action deathDate;
Action implicitly refers to a delegate.


 Func– A Func delegate defines a method that can be called on arguments and returns a result.
Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);

 Predicate– Defines a method that can be called on arguments and always returns the bool.
Predicate<string> myDel is same as delegate bool myDel(string s);
Q #34) What do Multicast Delegates mean?
Answer: A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and +=
operator.
Consider the example from Q #32.
There are two subscribers for deathEvent, GetPatInfo, and GetDeathDetails. And hence we have used += operator. It means whenever
the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.
Q #35) Explain Publishers and Subscribers in Events.
Answer: Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but Event
as discussed in the above questions.
From the Example in Q #32, Class Patient is the Publisher class. It is generating an Event deathEvent, which is received by the other
classes.
Subscribers capture the message of the type that it is interested in. Again, from the Example of Q#32, Class Insurance and Bank are
Subscribers. They are interested in event deathEvent of type void.
Q #36) What are Synchronous and Asynchronous operations?
Answer: Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time. The
asynchronous call waits for the method to complete before continuing with the program flow.
Synchronous programming badly affects the UI operations when the user tries to perform time-consuming operations since only one
thread will be used. In Asynchronous operation, the method call will immediately return so that the program can perform other operations
while the called method completes its work in certain situations.

In C#, Async and Await keywords are used to achieve asynchronous programming. Look at Q #43 for more details on synchronous
programming.

Q #37) What is Reflection in C#?


Answer: Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and
uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.
The namespace System.Reflection contains methods and classes that manage the information of all the loaded types and methods. It is
mainly used for windows applications, For Example, to view the properties of a button in a windows form.
The MemberInfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as
methods and properties.

To get type of a class, we can simply use,


Type mytype = myClass.GetType();

Once we have a type of class, the other information about the class can be easily accessed.

System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);


Above statement tries to find a method with name AddNumbers in the class myClass.
Q #38) What is a Generic Class?
Answer: Generics or Generic class is used to create classes or objects which do not have any specific data type. The data type can be
assigned during runtime, i.e when it is used in the program.
For Example:
So, from the above code, we see 2 compare methods initially, to compare string and int.

In case of other data type parameter comparisons, instead of creating many overloaded methods, we can create a generic class and
pass a substitute data type, i.e T. So, T acts as a datatype until it is used specifically in the Main() method.

Q #39) Explain Get and Set Accessor properties?


Answer: Get and Set are called Accessors. These are made use by Properties. The property provides a mechanism to read, write the
value of a private field. For accessing that private field, these accessors are used.
Get Property is used to return the value of a property
Set Property accessor is used to set the value.
The usage of get and set is as below:

Q #40) What is a Thread? What is Multithreading?


Answer: A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing.
Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be
created to execute the code in parallel with the original thread.
Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the
namespace which needs to be included to create threads and use its members.
Threads are created by extending the Thread Class. Start() method is used to begin thread execution.
//CallThread is the target method//

ThreadStart methodThread = new ThreadStart(CallThread);

Thread childThread = new Thread(methodThread);

childThread.Start();

C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called
MultiThreading.

There are several thread methods that are used to handle multi-threaded operations:
Start, Sleep, Abort, Suspend, Resume and Join.

Most of these methods are self-explanatory.

Q #41) Name some properties of Thread Class.


Answer: Few Properties of thread class are:
 IsAlive – contains value True when a thread is Active.
 Name – Can return the name of the thread. Also, can set a name for the thread.
 Priority – returns the prioritized value of the task set by the operating system.
 IsBackground – gets or sets a value which indicates whether a thread should be a background process or foreground.
 ThreadState– describes the thread state.
Q #42) What are the different states of a Thread?
Answer: Different states of a thread are:
 Unstarted – Thread is created.
 Running – Thread starts execution.
 WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
 Suspended – Thread has been suspended.
 Aborted – Thread is dead but not changed to state stopped.
 Stopped – Thread has stopped.
Q #43) What are Async and Await?
Answer: Async and Await keywords are used to create asynchronous methods in C.
Asynchronous programming means that the process runs independently of main or other processes.

Usage of Async and Await is as shown below:

 Async keyword is used for the method declaration.


 The count is of a task of type int which calls the method CalculateCount().
 Calculatecount() starts execution and calculates something.
 Independent work is done on my thread and then await count statement is reached.
 If the Calculatecount is not finished, myMethod will return to its calling method, thus the main thread doesn’t get blocked.
 If the Calculatecount is already finished, then we have the result available when the control reaches await count. So the next step
will continue in the same thread. However, it is not the situation in the above case where the Delay of 1 second is involved.
Q #44) What is a Deadlock?
Answer: A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for
each other to finish. This usually occurs in multi-threading.
Here a shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding
the locked item is waiting for another process to complete.

Consider the below Example:


Perform tasks accesses objB and waits for 1 second.
Meanwhile, PerformtaskB tries to access ObjA.
After 1 second, PeformtaskA tries to access ObjA which is locked by PerformtaskB.
PerformtaskB tries to access ObjB which is locked by PerformtaskA.
This creates Deadlock.

Q #45) Explain Lock, Monitors, and Mutex Object in Threading.


Answer: Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example,
lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.
Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to
release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.

Monitor.Enter(ObjA);

try

Finally {Monitor.Exit(ObjA));}

Q #46) What is a Race Condition?


Ans: Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which
will be able to access the resource first cannot be predicted.
If we have two threads, T1 and T2, and they are trying to access a shared resource called X. And if both the threads try to write a value
to X, the last value written to X will be saved.

Q #47) What is Thread Pooling?


Ans: Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the
thread completes the task, the thread returns to the pool.
System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.

System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SomeTask));

The above line queues a task. SomeTask methods should have a parameter of type Object.

Q #48) What is Serialization?


Answer: Serialization is a process of converting code to its binary format. Once it is converted to bytes, it can be easily stored and
written to a disk or any such storage devices. Serializations are mainly useful when we do not want to lose the original form of the code
and it can be retrieved anytime in the future.
Any class which is marked with the attribute [Serializable] will be converted to its binary form.

The reverse process of getting the C# code back from the binary form is called Deserialization.

To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace
System.Runtime.Serialization can contain classes for serialization.

Q #49) What are the types of Serialization?


Answer: The different types of Serialization are:
 XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily
read and manipulated in various formats. The classes reside in System.sml.Serialization.
 SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that
can be used by any system that understands SOAP.
 Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public
properties. It is faster and occupies less space.
Q #50) What is an XSD file?
Answer: An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the
XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have
any tags, any attributes, and any elements.
Xsd.exe tool converts the files to the XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by
xsd.exe.

Conclusion
C# is growing rapidly day by day and it plays a major role in the Software Testing Industry.

I am sure that this article will make your preparation for the interview much easier and give you a fair amount of knowledge of most of the
C# topics.

Hope you would be ready to face any C# interview confidently!!

https://www.wisdomjobs.com/e-university/advanced-c-hash-interview-questions.html

1. Question 1. What Is Attribute In C#?


Answer :
An attributes is a declarative tag that is used to convey information about the behaviors of various elements (classes, methods,
assemblies, structures, enumerators, etc). it is access at compile time or run-time. Attributes are declare with a square brackets []
which is places above the elements.
[Obsolete(“Don’t use Old method, please use New method”, true)]
For example consider the bellow class. If we call the old method it will through error message.
public class myClass
{
[Obsolete("Don't use Old method, please use New method", true)]
public string Old() { return "Old"; }
public string New() { return "New"; }
}
myClass omyClass = new myClass();
omyClass.Old();
2. Question 2. Why Attributes Are Used?
Answer :
In a program the attributes are used for adding metadata, like compiler instruction or other information (comments, description, etc).

C#. NET Interview Questions

3. Question 3. What Are The Types Of Attributes?


Answer :
The Microsoft .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.
Pre-define attributes are three types:
o AttributeUsage
o Conditional
o Obsolete
This marks a program that some entity should not be used.
4. Question 4. What Is Custom Attributes?
Answer :
The Microsoft .Net Framework allows creating custom attributes that can be used to store declarative information and can be retrieved
at run-time.

C#. NET Tutorial

5. Question 5. What Is Reflection?


Answer :
Reflection is a process by which a computer program can monitor and modify its own structure and behavior. It is a way to explore
the structure of assemblies at run time (classes, resources, methods). Reflection is the capability to find out the information about
objects, metadata, and application details (assemblies) at run-time. We need to include System.Reflection namespace to perform
reflections in C#. For example consider the following C# codes, which will returns some meta information’s.
public class MyClass
{
public virtual int Add(int numb1, int numb2)
{
return numb1 + numb2;
}
public virtual int Subtract(int numb1, int numb2)
{
return numb1 - numb2;
}
}
static void Main(string[] args)
{
MyClass oMyClass = new MyClass();
//Type information.
Type oMyType = oMyClass.GetType();
//Method information.
MethodInfo oMyMethodInfo = oMyType.GetMethod("Subtract");
Console.WriteLine("nType information:" + oMyType.FullName);
Console.WriteLine("nMethod info:" + oMyMethodInfo.Name);
Console.Read();
}

C Interview Questions

6. Question 6. Why We Need Reflection In C#?


Answer :
Reflections needed when we want to determine / inspect contents of an assembly. For example: at Visual Studio editor intelligence,
when we type “.” (dot) before any object, it gives us all the members of the object. This is possible for Reflection.
Beside this we need reflection for the following purposes:
o To view attribute information at run time
o To view the structure of assemblies at run time (classes, resources, methods)
o It allows dynamic/late binding to methods and properties
o In serialization, it is used to serialize and de-serialize objects
o In web service, it is used to create and consume SOAP messages and also to generate WSDL
o Debugging tools can use reflection to examine the state of an object.
7. Question 7. What Is Dynamic Keyword?
Answer :
The dynamic is a keyword which was introduced in .NET 4.0. Computer programming languages are two types: strongly typed and
dynamically typed. In strongly types all types checks are happened at compile time, in dynamic types all types of checks are happened
at run time.
For example consider the following code
dynamic x = "c#";
x++;
It will not provide error at compile time but will provide error at run time.

C Tutorial ASP.NET Interview Questions

8. Question 8. When To Use Dynamic?


Answer :
The biggest practical use of the dynamic keyword is when we operate on MS Office.
9. Question 9. What Is The Difference Between Reflection And Dynamic?
Answer :
Both Reflection and dynamic are used to operate on an object during run time. But they have some differences:
o Dynamic uses reflection internally
o Reflection can invoke both public and private members of an object. But dynamic can only invoke public members of an
object
C & Data Structures Interview Questions

10. Question 10. What Is Serialization?


Answer :
When we want to transport an object through network then we need to convert the object into a stream of bytes. Serialization is a
process to convert a complex objects into stream of bytes for storage (database, file, cache, etc) or transfer. Its main purpose is to save
the state of an object.
De-serialization is the reverse process of creating an object from a stream of bytes to their original form.

ASP.NET Tutorial

11. Question 11. What Are The Types Of Serialization?


Answer :
The types of Serializations are given bellow:
1 Binary Serialization
In this process all the public, private, read only members are serialized and convert into stream of bytes. This is used when we
want a complete conversion of our objects.
2 SOAP Serialization
In this process only public members are converted into SOAP format. This is used in web services.
3 XML Serialization
In this process only public members are converted into XML. This is a custom serialization. Required namespaces:
System.Xml, System.Xml.Serialization.
Windows Presentation Foundation(WPF) Interview Questions

12. Question 12. Why Serialization And Deserialization?


Answer :
For example consider, we have a very complex object and we need XML format to show it on HTML page. Then we can create a
XML file in the disk, writes all the necessary data on the XML file, and use it for the HTML page. But this is not good approach for
large number of users. Extra space is required; anyone can see the XML file which creates security issue. We can overcome it by
using XML serialization.

C#. NET Interview Questions

13. Question 13. When To Use Serialization?


Answer :
Serialization is used in the following purposes:
o To pass an object from on application to another
o In SOAP based web services
o To transfer data through cross platforms, cross devices

Windows Presentation Foundation(WPF) Tutorial

14. Question 14. Give Examples Where Serialization Is Used?


Answer :
Serialization is used to save session state in ASP.NET applications, to copy objects to the clipboard in Windows Forms. It is also used
to pass objects from one application domain to another. Web services uses serialization.
15. Question 15. What Is Generics?
Answer :
Generics are the most powerful features introduced in C# 2.0. It is a type-safe data structure that allows us to write codes that works
for any data types.

Windows Communication Foundation (WCF) Interview Questions

16. Question 16. What Is A Generic Class?


Answer :
A generic class is a special kind of class that can handle any types of data. We specify the data types during the object creations of that
class. It is declared with the bracket <>. For example consider the following Comparer class, which has a method that compare two
value and returns as Boolean output.
public class Comparer
{
public bool Compare(Unknown t1, Unknown t2)
{
if (t1.Equals(t2))
{
return true;
}
else
{
return false;
}
}
}
Comparer oComparerInt = new Comparer();
Console.WriteLine(oComparerInt.Compare(10, 10));
Comparer oComparerStr = new Comparer();
Console.WriteLine(oComparerStr.Compare("jdhsjhds", "10"));

Windows Communication Foundation (WCF) Tutorial

17. Question 17. Why We Should Use Generics?


Answer :
Generic provides lot of advantages during programming. We should use generics for the following reasons:
o It allows creating class, methods which are type-safe
o It is faster. Because it reduce boxing/un-boxing
o It increase the code performance
o It helps to maximize code reuse, and type safety

C and C++ Interview Questions

18. Question 18. What Is Collections In C#?


Answer :
Sometimes we need to work with related objects for data storage and retrieval. There are two ways to work with related objects. One
is array and another one is collections. Arrays are most useful for creating and working with a fixed number of strongly-typed objects.
Collections are enhancement of array which provides a more flexible way to work with groups of objects.
The Microsoft .NET framework provides specialized classes for data storage and retrieval. Collections are one of them. Collection is a
data structure that holds data in different ways. Collections are two types. One is standard collections, which is found under
System.Collections namespace and another one is generic collections, which is found under System.Collections.Generic
namespace.The generic collections are more flexible and preferable to work with data.
Some commonly used collections under System.Collections namespace are given bellow:
o ArrayList
o SortedList
o Hashtable
o Stack
o Queue
o BitArray

C Interview Questions

19. Question 19. What Is Unsafe Code?


Answer :
In order to maintain security and type safety, C# does not support pointer generally. But by using unsafe keyword we can define an
unsafe context in which pointer can be used. The unsafe code or unmanaged code is a code block that uses a pointer variable. In the
CLR, unsafe code is referred to as unverifiable code. In C#, the unsafe code is not necessarily dangerous. The CLR does not verify its
safety. The CLR will only execute the unsafe code if it is within a fully trusted assembly. If we use unsafe code, it is our own
responsibility to ensure that the code does not introduce security risks or pointer errors.
20. Question 20. What Are The Properties Of Unsafe Code?
Answer :
Some properties of unsafe codes are given bellow:
o We can define Methods, types, and code blocks as unsafe
o In some cases, unsafe code may increase the application’s performance by removing array bounds checks
o Unsafe code is required in order to call native functions that require pointers
o Using unsafe code brings security and stability risks
o In order to compile unsafe code, the application must be compiled with /unsafe
C# OOPS Interview Questions

21. Question 21. Can Unsafe Code Be Executed In Untrusted Environment?


Answer :
Unsafe code cannot be executed in an un-trusted environment. For example, we cannot run unsafe code directly from the Internet.
22. Question 22. How To Compile Unsafe Code?
Answer :
For compiling unsafe code, we have to specify the /unsafe command-line switch with command-line compiler.
For example: to compile a program named “myClass.cs” containing unsafe code the command line command is:
csc /unsafe myClass.cs
In Visual Studio IDE at first we need to enable use of unsafe code in the project properties.
The steps are given bellow:
o Open project properties
o Click on the Build tab
o Select the option “Allow unsafe code”
23. Question 23. What Is Pointer?
Answer :
Pointer is a variable that stores the memory address of another variable. Pointers in C# have the same capabilities as in C or C++.
Some examples are given bellow:
o int *i // pointer of an integer
o float *f // pointer to a float
o double *d // pointer to a double
o char *ch // pointer to a character

C# Developer Multi Threading Interview Questions

24. Question 24. Should I Use Unsafe Code In C#?


Answer :
In C#, pointer is really used and Microsoft disengaged to use it. But there are some situations that require pointer. We can use pointer
if required at our own risk. Some sonorous are given bellow:
o To deal with existing structures on disk
o Some advanced COM or Platform Invoke scenarios that involve pointer
o To performance critical codes

ASP.NET Interview Questions

25. Question 25. How Can We Sort The Elements Of The Array In Descending Order ?
Answer :
For This,First we call the Sort () method and then call Reverse() Methods.
26. Question 26. Can We Store Multiple Data Types In System.array ?
Answer :
No.
27. Question 27. What Is The Difference Between The System.array.copyto() And System.array.clone() ?
Answer :
System.Array.CopyTo()-->It require a destination array to be existed before and it must be capable to hold all the elements in the
source array from the index that is specified to copy from the source array.
System.Array.Clone()-->It does not require the destination array to be existed as it creates a new one from scratch.
Note-These both are used as a shallow copy.

C & Data Structures Interview Questions

28. Question 28. What Is Difference Between String And Stringbuilder ?


Answer :
StringBuilder is more efficient than string.
String :- It is Immutable and resides within System Namespace.
StringBuilder:-It is mutable and resides System.Text Namespace.
29. Question 29. What Is Class Sortedlist Underneath?
Answer :
It is a Hash Table.
30. Question 30. What Is The .net Data Type That Allow The Retrieval Of Data By A Unique Key ?
Answer :
Hash Table
31. Question 31. Is Finally Block Get Executed If The Exception Is Not Occured ?
Answer :
Yes.
32. Question 32. Can Multiple Catch () Block Get Executed If The Exception Is Not Occured ?
Answer :
No,Once the proper catch code fires off ,the control is transferred to the finally block(if any),and the whatever follows the finally
block.
33. Question 33. What Is Multicast Delegate ?
Answer :
The Multicast delegate is a delegate that points to and eventually fires off several methods.

Windows Presentation Foundation(WPF) Interview Questions

34. Question 34. What Are The Ways To Deploy An Assembly ?


Answer :
o An MSI Installer
o A CAB archive
o XCopy command
35. Question 35. What Is The Dll Hell Problem Solved In .net ?
Answer :
In .NET, Assembly versioning allows the application to specify not only the library it needs to run ,but also the version of the
assembly.
36. Question 36. What Is A Satellite Assembly ?
Answer :
When we write the code, a multicultural or multilingual application in .NET and want to distribute the core application separately
from the localized modules,the localized assemblies that modify the core application ,that is known as Satellite assembly.

Windows Communication Foundation (WCF) Interview Questions


37. Question 37. How Do We Inherit From A Class In C# ?
Answer :
In c#, we use a colon (:) and then the name of the base class.
38. Question 38. Does C# Support Multiple Inheritance ?
Answer :
No, we use interface for this purpose.
39. Question 39. Are Private Class -label Variables Inherited ?
Answer :
Yes, but it is not accessible.we generally know that they are inherited but not accessible.
40. Question 40. What Is The Implicit Name Of The Parameter That Gets Passed Into Class "set" Method ?
Answer :
Value and it's datatype(it depends whatever variable we are changing).

C and C++ Interview Questions

41. Question 41. What Is The Top .net Class ?


Answer :
System.Object
42. Question 42. How Does Method Overloading Different From Overriding ?
Answer :
A method overloading simply involves having a method with the same name within the class. whereas in method overriding we can
change method behaviour for a derived class.

C# OOPS Interview Questions

43. Question 43. Can We Override Private Virtual Method ?


Answer :
No.
44. Question 44. Can We Declare The Override Method Static While The Original Method Is Non Static ?
Answer :
No.
45. Question 45. Can We Prevent My Class From Being Inherited And Becoming A Base Class From The Other Classes ?
Answer :
Yes.
46. Question 46. What Is An Interface Class ?
Answer :
This is an abstract class with public abstract methods , all of which must be implemented in the inherited classes.
47. Question 47. Can We Inherit Multiple Interfaces ?
Answer :
Yes.
48. Question 48. Can We Allow Class To Be Inherited ,but Prevent The Method From Being Overridden ?
Answer :
Yes, first create class as public and make it's method sealed.
49. Question 49. What Is Signature Used For Overloaded A Method ?
Answer :
o Use different data types
o Use different number of parameters
o Use different order of parameters
50. Question 50. What Is The Difference Between An Interface And Abstract Class ?
Answer :
In an interface, all methods must be abstract but in abstract class some methods can be concrete.In interface No accessibility modifiers
are alloweded but in abstract class a accessibility modifier are alloweded.

Advanced C# Related Tutorials


C#. NET Tutorial C Tutorial

ASP.NET Tutorial Windows Presentation Foundation(WPF) Tutorial

Windows Communication Foundation (WCF) Tutorial


Advanced C# Related Tutorials

Advanced C# Related Interview Questions


C#. NET Interview Questions C Interview Questions

ASP.NET Interview Questions C & Data Structures Interview Questions

Windows Presentation Foundation(WPF) Interview Questions Windows Communication Foundation (WCF) Interview Questions

C and C++ Interview Questions C# OOPS Interview Questions

C# Developer Multi Threading Interview Questions

Advanced C# Related Practice Tests


C#. NET Practice Tests C Practice Tests

ASP.NET Practice Tests C & Data Structures Practice Tests

Windows Presentation Foundation(WPF) Practice Tests Windows Communication Foundation (WCF) Practice Tests

What is delegate?
Delegates are objects you can use to call the methods of other objects.
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented,
type safe, and secure. The type of a delegate is defined by the name of the delegate.
Once a delegate is assigned a method, it behaves exactly like that method.
The delegate method can be invoked like any other method, with parameters and a return value.
Any method from any accessible class or struct that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the
delegate.
The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing
classes. As long as you know the signature of the delegate, you can assign your own delegated method.
Delegates have the following properties:
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.
What is the difference between method overloading and delagate?
In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include
the return value.
Why callback methods use delegates?
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference
to the method that compares two objects. Separating the comparison code allows for the algorithm to be written in a more general way.
What is the importance of delegates and events in designing large applications?
The use of delegates and events in the design of a large application can reduce dependenciesand the coupling of layers.This allows you to develop components
that have a higher reusability factor.
What are the uses of delegates/callback functions?
1)to sort elements within an array.
2)callback functions are required for window procedures, hook procedures, asynchronous procedure calls.
3) to get assembly load/unload notifications, unhandled exception notifications, database/window state change notifications, file system change notifications,
menu item selections, completed asynchronous operation notifications, filtering a set of items, and so on.
4)Delegates are useful in situations where you need an intermediary between a calling procedure and the procedure being called.
5)You can use delegates for other, non-event related tasks, such as free threading or with procedures that need to call different versions of functions at
compile time.
e.g:suppose you have a classified-ad application that includes a list box with the names of cars. The ads are sorted by title, which is normally the make of the
car. A problem you may face occurs when some cars include the year of the car before the make. The problem is that the built-in sort functionality of the list
box sorts only by character codes; it places all the ads starting with dates first, followed by the ads starting with the make.
To fix this, you can create a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to switch at run time to the custom
sort procedure for car ads. To do this, you pass the custom sort procedure to the sort class at run time, using delegates.
6)The use of delegates promotes good separation of functionality between the database and the client code.
What is Delegate invocation?
A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method. Once a delegate is
instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed
to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate.
What is asynchronous callback ?
Delegate types are sealed—they cannot be derived from— and it is not possible to derive custom classes from Delegate. Because the instantiated delegate is an
object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later
time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed. When a delegate is used in
this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the
encapsulation interfaces provide.
When to Use Delegates Instead of Interfaces?
Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented
by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface
reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. Given these similarities,
when should a class designer use a delegate and when should it use an interface?
Use a delegate in the following circumstances:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the method.
Use an interface in the following circumstances:
There is a group of related methods that may be called.
A class only needs one implementation of the method.
The class using the interface will want to cast that interface to other interface or class types.
The method being implemented is linked to the type or identity of the class: for example, comparison methods.
What are Events?
Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the
publisher and the classes that receive (or handle) the event are called subscribers.
Events have the following properties:
The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
Events that have no subscribers are never called.
Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised.
Events can be used to synchronize threads.
In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.
How will you subscibe to events?
Using event Handler
Define an event handler method whose signature matches the delegate signature for the event. For example, if the event is based on the EventHandler
delegate type, the following code represents the method stub:
void HandleCustomEvent(object sender, CustomEventArgs a)
{ // Do something useful here. }
Use the addition assignment operator (+=) to attach your event handler to the event. In the following example, assume that an object named publisher has an
event named RaiseCustomEvent. Note that the subscriber class needs a reference to the publisher class in order to subscribe to its events.
publisher.RaiseCustomEvent += HandleCustomEvent;
An event handler can also be added by using a lambda expression:
public Form1()
{
InitializeComponent();
// Use a lambda expression to define an event handler.
this.Click += (s,e) => { MessageBox.Show(
((MouseEventArgs)e).Location.ToString());};
}
To subscribe to events by using an anonymous method:
Use the addition assignment operator (+=) to attach your anonymous method to the event.
In the following example, assume that an object named publisher has an event named RaiseCustomEvent and that a CustomEventArgs class has also been
defined to carry some kind of specialized event information. Note that the subscriber class needs a reference to publisher in order to subscribe to its events.
publisher.RaiseCustomEvent += delegate(object o, CustomEventArgs e)
{ string s = o.ToString() + " " + e.ToString();
Console.WriteLine(s);
};
How to unsubscibe from event?
To prevent your event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, you should
unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the
publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference,
garbage collection will not delete your subscriber object.
To unsubscribe from an event
Use the subtraction assignment operator (-=) to unsubscribe from an event:
publisher.RaiseCustomEvent -= HandleCustomEvent;
What is Multicast delegate?
Multicast delegates can be defined as delegates that have more than one element in their invocation list. In other words, it is a delegate that is subscribed by
more than one method.
A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the
delegates in the invocation list are called synchronously in the order in which they appear. If an error occurs during execution of the list then an exception is
thrown.
How will you handle Exceptions in multicast delegates?
Suppose you have added multiple delegates to a single multicast delegate. Each of these individual delegates must be invoked, regardless of whether an
unhandled exception is thrown within one of the delegates. But, once a delegate in a multicast delegate throws an unhandled exception, no more delegates are
fired. You need a way to trap unhandled exceptions within each individual delegate while still allowing the rest of the delegates to fire.
To avoid breaking the chain, you have to gracefully handle exceptions in all functions. Use the GetInvocationList method. This method returns each individual
delegate from a multicast delegate and, by doing so, allows you to invoke each delegate within the try block of an exception handler.
Expain Anonymous Methods in Delegates?
Sometimes, you want to use a very small amount of code to call a delegate. Creating functions for such a small code will make the code cumbersome and
difficult to read and debug. C# 2.0 comes with a new concept of Anonymous methods. By using anonymous methods, you reduce the overhead in instantiating
delegates by eliminating the need of separate method. Here is the small example to illustrate
this./************************************************************/
AddDelegate add = delegate (int k) {return a + b;};
/************************************************************/
Explain Covariance and Contravariance in Delegates ?
These provide a degree of flexibility while matching delegate methods with delegate signatures.
Covariance:Covariance permits a method with a derived return type to be used as a delegate. When a delegate method has a return type that is derived from
the return type of delegate, it is called a covariant. Because the return type of method is derived from the return type of delegate, the type conversion is
implicit. This enables you to create delegate methods that can be used by base and derived classes.
/************************************************************/
public class BaseClass {
// Some functions}
public class DerivedClass : BaseClass
{ // Some functions}
public class MainClass{ // Define a delegate delegate BaseClass TestDelegate(); private static DerivedClass ReturnDerived()
{ return new DerivedClass(); }
public static void Main(string []args) { // Covariance allows this TestDelegate delg = ReturnDerived;
}}/************************************************************/
Contravariance:
Contravariance permits a method with derived parameters to be used as a delegate. When a delegate method signature has parameters that are derived from
the delegate parameters, the method is said to be contravariant./************************************************************/
public class BaseClass
{
// Some functions
}
public class DerivedClass : BaseClass
{
// Some functions
}
public class MainClass
{
// Define a delegate
delegate BaseClass TestDelegate(BaseClass baseClassArg);
private static DerivedClass ReturnDerived(DerivedClass dr)
{
return dr;
}
public static void Main(string []args)
{
// Contravariance allows this
TestDelegate delg = ReturnDerived;
}
}
/************************************************************/
What is event Handler?
Event handlers are nothing more than methods that are invoked through.
How do you declare delegates?
e.g:public delegate void ProcessBookDelegate(Book book);
How do you instantiate a delegate?
e.g:bookDB.ProcessPaperbackBooks(PrintTitle);
How do you call a delegate?
processBook(b);
Explain how delegates are used in asynchronous programming?
Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target
method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately
to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to
continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is
called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters.
If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.
Note:Compilers should emit delegate classes with Invoke, BeginInvoke, and EndInvoke methods using the delegate signature specified by the user. The
BeginInvoke and EndInvoke methods should be decorated as native. Because these methods are marked as native, the CLR automatically provides the
implementation at class load time. The loader ensures that they are not overridden.
Expain about BeginInvoke method of delegates?
The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two
additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes.
The second parameter is a user-defined object that passes information into the callback method. BeginInvoke returns immediately and does not wait for the
asynchronous call to complete. BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call.
Expain about EndInvoke method?
The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed,
EndInvoke blocks the calling thread until it completes. The parameters of EndInvoke include the out and ref parameters
of the method that you want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.
How to obtain Waithandle ?
You can obtain a WaitHandle by using the AsyncWaitHandle()property of the IAsyncResult returned by BeginInvoke.
Explain about WaitHandle?
You can obtain a WaitHandle by using the AsyncWaitHandle()property of the IAsyncResult returned by BeginInvoke.The WaitHandle is signaled when the
asynchronous call completes, and you can wait for it by calling the WaitOne()method.
If you use a WaitHandle, you can perform additional processing before or after the asynchronous call completes, but before calling EndInvoke to retrieve the
results.
Note:The wait handle is not closed automatically when you call EndInvoke. If you release all references to the wait handle, system resources are freed
when garbage collection reclaims the wait handle. To free the system resources as soon as you are finished using the wait handle, dispose of it by calling the
WaitHandleClose()method. Garbage collection works more efficiently when disposable objects are explicitly disposed.
How will you know when the asynchronous call completes?
use the IsCompleted() property of the IAsyncResult returned by BeginInvoke .
When Asynchronous operations are used?
Asynchronous operations are typically used to perform tasks that might take a long time to complete, such as opening large files, connecting to remote
computers, or querying a database. An asynchronous operation executes in a thread separate from the main application thread. When an application calls
methods to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.
What are the design patterns .Net provides to accomplish asynchronous operations?
The .NET Framework provides two design patterns for asynchronous operations:
Asynchronous operations that use IAsyncResult objects.
Asynchronous operations that use events.
The IAsyncResult design pattern allows for a variety of programming models, but is more complex to learn and provides a flexibility that most applications do
not require. Where possible, class library designers should implement asynchronous methods using the event-driven model.
where Asynchronous programming feature supported in .Net?
Asynchronous programming is a feature supported by many areas of the .NET Framework, including:
File IO, Stream IO, Socket IO.
Networking.
Remoting channels (HTTP, TCP) and proxies.
XML Web services created using ASP.NET.
ASP.NET Web Forms.
Message Queuing using the MessageQueue class.

Suppose in a scenario if we want to display information only until 4.00 p.m and after that means after 4.00 p.m if any one tries to access
the information it should give error mesage. Then how will you write a delegate for this ? Give coding. (Question from
allinterviews.com)

delegate void InformDelegate();


class Program
{
static void Main(string[] args)
{
InformDelegate info = null;
Display disp =new Display();
if (DateTime.Now.Hour < 16) { info = new InformDelegate(disp.morning); } else { info = null;

}
}
class Display
{
public void morning()
{
Console.WriteLine("display");
}
public void Evening()
{
Console.WriteLine("You are not allowed to access the information in this time. Try tommarrow morning");
}
}

Duplicate letter in a string


In C#

You might also like