Static: Calculator
Static: Calculator
Static: Calculator
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;
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
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 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
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
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.
Repository Pattern
A Class
Encapsulation
A Class
Abstraction
A Class
Polymorphism
A Class
Runtime 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.
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.
// 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!");
class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
del("Hello World");
del = ClassB.MethodB;
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);
}
}
class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
InvokeDelegate(del);
del = ClassB.MethodB;
InvokeDelegate(del);
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 del3 = (string msg) => Console.WriteLine("Called lambda expression: " + msg);
del += del3; // combines del1 + del2 + del3
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.
class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;
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));
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.
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;
}
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.
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.
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.
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
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.
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.
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();
}
}
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:
The first parameter specifies the function that we want to execute on the pool. Its signature must match the delegate WaitCallback.
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.
ReactiveX
Thread
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.
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)
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
}
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;
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; }
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();
}
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.
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 ";
}
}
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());
}
}
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();
}
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();
}
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.
Creational Patterns
Note
The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First President of States).
Structural Patterns
Note
Behavioral Patterns
Note : In the further section we will be covering all the above design patterns in a more detail manner.
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.
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.
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.
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.
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.
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
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'.
Now we display both the values and we have found that both the objects have the new value.
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.
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
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.
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();
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();
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.
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."
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
· 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 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
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?
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?
The .NET Framework's garbage collector manages the allocation and release of memory for your application.
for destructor :
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
For Dispose:
TestObj.Dispose();
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.
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.
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.
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
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.
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.
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 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.
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.
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.
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.
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.
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.
For more information, see the article: Gathering SQL Server indexes statistics and usage information.
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.
Stored Procedure
Below are the list of Best Stored procedures Interview questions and Answers
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.
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.
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.
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.
The various tips and tricks for optimising a stored procedure optimization are listed below:
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:
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.
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.
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”);
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.
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
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.
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.
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.
Example:
Example:
Eg:
/// summary;
/// Set error message for multilingual language.
/// summary
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.
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.
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.
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.
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.
We can't use 'This' in a static method because we can only use static variables/methods in a static method.
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.
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();
}
pTutor.SetTutorial(1,".Net by Guru99");
Console.WriteLine(pTutor.GetTutorial());
Console.ReadKey();
}
}
}
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.
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.
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.
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.
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?
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.
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.
Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition
and make the resources unusable.
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.
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.
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.
Colon is used as inheritance operator in C#. Just place a colon and then the class name.
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.
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.
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.
Value types can take either their normal values or a null value. Such types are called nullable types.
"is" operator is used to check the compatibility of an object with a given type, and it returns the result as Boolean.
A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is assigned to a method.
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:
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.
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:
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.
C# is managed code because Common language runtime can compile C# code to Intermediate language.
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.
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);
https://www.fullstack.cafe/blog/c-sharp-interview-questions
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
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
linkc-sharpcorner.com
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.
HTML5 55
Vue.js 41
Webpack 32
Behavioral 112
Reactive Programming 27
ADO.NET 33
MSMQ 16
Bootstrap 38
MongoDB 82
Ionic 29
PWA 22
Software Testing 26
Java 147
Python 96
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.
linkc-sharpcorner.com
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
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.
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
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.
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.
linkguru99.com
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
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.
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
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
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.
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
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.
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.
linkc-sharpcorner.com
Vue.js 41
PHP 82
Code Problems 26
Laravel 41
WPF 46
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.
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.
linkc-sharpcorner.com
Data Structures 30
Golang 49
WebSockets 24
CSS 50
Software Testing 26
Ionic 29
AngularJS 62
Spring 87
WPF 46
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
}
}
linkstackoverflow.com
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"
};
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.
linkguru99.com
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.
linksoftwaretestinghelp.com
Code Problems 26
Xamarin 83
Bootstrap 38
WebSockets 24
HTML5 55
ADO.NET 33
CSS 50
jQuery 51
Android 113
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.
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:
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.
linktoptal.com
#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
C# 112
Mid
Details
class ClassA
{
public ClassA() { }
// 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)
{ }
linktoptal.com
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.
linkdocs.microsoft.com
Xamarin 83
ADO.NET 33
Entity Framework 57
Behavioral 112
Python 96
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
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
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
TypeScript 39
Ionic 29
C# 112
Senior
Answer
#Angular
Q27: Describe the accessibility modifier "protected internal". Describe the accessibility modifier "protected internal".
C# 112
Senior
Answer
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
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
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
Q31: Why to use lock statement in C#? Why to use lock statement in C#?
C# 112
Senior
Answer
#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;
C# 112
Senior
Details
Consider:
class Program {
private static string result;
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 TestStatic() {
if (TestValue == 0) {
TestValue = 5;
}
}
static TestStatic() {
if (TestValue == 0) {
TestValue = 10;
}
}
}
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
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
#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
MSMQ 16
Microservices 34
Entity Framework 57
CSS 50
PWA 22
React 164
Golang 49
WCF 33
Laravel 41
Java 147
MongoDB 82
Design Patterns 45
jQuery 51
C# 112
Expert
Answer
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
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.
Easy to learn
Object oriented
Component oriented
Part of .NET framework
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.
class X {}
sealed class Y : X {}
Sealed methods –
class A
}
class B : A
If any class inherits from class “B” then method – “First” will not be overridable as this method is sealed in class B.
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.
“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.
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.
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.
“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.
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.
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.
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.
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.
class
string
interface
object
No. We can’t override private virtual methods as it is not accessible outside the class.
“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 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
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.
NullReferenceException
ArgumentNullException
DivideByZeroException
IndexOutOfRangeException
InvalidOperationException
StackOverflowException etc.
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.
Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.
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.
Single Delegate
Multicast Delegate
Generic Delegate
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.
Callback Mechanism
Asynchronous Processing
Abstract and Encapsulate method
Multicasting
double mySecno;
50) What is the difference between “as” and “is” operators in C#?
A delegate with multiple handlers are called as multicast delegate. The example to demonstrate the same is given below
int x = 6;
int y = 7;
multiCast.Invoke(a,b);
C# code is managed code because the compiler – CLR will compile the code to Intermediate Language.
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,
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");
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
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#?
Using System.IO;
File.WriteAllText(”mytextfilePath”, “MyTestContent”);
Boxing – This is the process of converting from value type to reference type. For example,
int myvar = 10;
UnBoxing – It’s completely opposite to boxing. It’s the process of converting reference type to value type. For example,
int myvar2 = (int)myObj;
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.
C# Compiler is – CSC.
If the constructor contains the same class in the constructor parameter then it is called as copy constructor.
class MyClass
prop1 = a;
prop2 = b;
prop1 = myobj.prop1;
prop2 = myobj.prop2;
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
{
prop1 = a;
prop2 = b;
Static MyClass()
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)
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>
public T this[int t]
get
return myArr[t];
set
myArr[t] = value;
}
}
ArrayList
Stack
Queue
SortedList
HashTable
Bit Array
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.
Conditional
Obsolete
Attribute Usage
Unstarted State
Ready State
Not Runnable State
Dead State
CurrentCulture
CurrentThread
CurrentContext
IsAlive
IsThreadPoolThread
IsBackground
Priority
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.
return name;
this.name = name;
return Salary;
}
Now we can access all the methods in the class “Employee” via object “John” as shown below.
John.setName(“XYZ”);
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.
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.
Let us explain this with the help of an example. In the code given below,
Employee emp1;
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.
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.
get
return minimumSalary;
}
set
minimumSalary = value;
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.
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);
Constructor overloading
Function overloading
Operator overloading
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 Employee()
{}
{}
}
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
{}
{}
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;
Width=w;
Height=h;
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.
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;
public Car()
}
public void DriveType()
public Ford()
}
public void Price()
CarFord.DriveType();
CarFord.Price();
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.
In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, use interface.
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
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()
{
public Ford()
{
Console.WriteLine("Derived Class Ford");
CarFord.DriveType();
Right Hand
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.
{
Console.WriteLine("Right Hand ");
public Car()
}
class Ford : Car
public Car()
{
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.
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()
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();
}
public Ford()
Console.WriteLine("Power Break");
Console.WriteLine("Bridgestone");
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.
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 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#.
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.
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. 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#
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#.
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#
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.
An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
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.
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
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
For more details, read the following article, Comparison of String and StringBuilder in C#.
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:
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.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
1. // Sealed class
2. sealed class SealedClass
3. {
4. }
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.
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#.
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.
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.
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#.
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
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];
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.
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.
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
Creating an Indexer
<modifier>
<return type>
A delegate in C# allows developers to treat methods as objects and invoke them from their code.
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#.
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. }
"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.
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#.
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.
To learn more about object pooling in C# and .NET, read the following, Object Pooling in .NET.
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:
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.
Modifier Description
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#?
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
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.
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.
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
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.
We can create anonymous types by using “new” keyword together with the object initializer.
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 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:
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.
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.
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.
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#.
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.
Inversion of Control and dependency injections are some techniques for getting loose coupling in modules.
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.
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.
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.
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.
public class SingletonExample { private static SingletonExample _Instance; private SingletonExample () { } public static
SingletonExample Get Instance() { if (_Instance == null) { _Instance = new SingletonExample (); } return _Instance; }}
Q22. Can we have only “try” block without “catch” block in C#?
Ans: Yes we can have only try block without catch block.
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.
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:
or:
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;
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
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.
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 ; }
Structs:
Do not support inheritance
Are value types
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);
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 ;
}
}
}
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() { }
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
{
namespace main1
{
class Program
{
try
{
Console.WriteLine( "Hello" );
}
catch (ArgumentNullException)
{
Console.WriteLine( "A" );
}
catch (Exception)
{
Console.WriteLine( "B" );
}
finally
{
Console.WriteLine( "C" );
}
Console.ReadKey();
}
}
}
Hide answer
Hello
C
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
{
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/
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.
Class is Pass by reference (reference type) Struct is Pass by Copy (Value type)
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”.
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
//----------------code to read-------------------//
//-------------code to write-------------------//
}
}
Console.writeline(“….”);
For Example:
abstract class AB1
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.
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.
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.
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.
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.
namespace ConsoleApp2
deathDate();
void GetDeathDetails()
void Main()
{
myPat.deathDate += GetDeathDetails;
void GetPatInfo ()
void Main()
myPat.deathDate += GetPatInfo;
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.
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.
Once we have a type of class, the other information about the class can be easily accessed.
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.
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.
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));}
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SomeTask));
The above line queues a task. SomeTask methods should have a parameter of type Object.
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.
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.
https://www.wisdomjobs.com/e-university/advanced-c-hash-interview-questions.html
C Interview Questions
ASP.NET Tutorial
C 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.
Windows Presentation Foundation(WPF) Interview Questions Windows Communication Foundation (WCF) Interview Questions
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)
}
}
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");
}
}