observer design pattern

Here is the definition of observer design pattern

The observer is know as a behavioral pattern, as it’s used to form relationship between object at run time. Its define a 1-m dependency objects so that when one object changes state, all its dependents are notified and update automatically.

Bounce! Bounce! Bounce!
OK, lets define above definition once more, little easy

In ODP an object called the subject, maintains a list of its dependents, called observers, and notify them automatically of any state change, usually by calling one of their method.

OK! OK! OK! little easy

In ODP, Observer and Subject are two interface, where all classes those implement Subject interface have a list of observer object to notify and classes those implement Observer interface have list of Subject object to be notify.

Ohhh GOD! last attempt.

Observer register with the subject and wait for notification.
Subject notify observer about a change in state. Observer take action.

When ODP come into action?

  • When we want to reduce coupling.
  • If we have an object that need to share it’s state with other, without knowing who those objects are, the observer pattern come into action.

Case Study
There is a terrorist group that the RAW(Research And Analysis Wing) are trying to catch.So we need a tracking system that track terrorist information immediately. We need to create a alert device, if terrorist are near.
There are following step we need to follow,

Step 1: Identify the observer and subject
In this case terrorist will be subject and RAW tracking device will be observer.
So we need to represent information about the terrorist in a few line of code which represent by a class.
/* A single terrorist has a location*/
class Terrorist
{
public string location;
}

The RAW device will be the observers. Which will push alert on critical notification.
/*A device has an alert status(as a Boolean), notification update(as a string), location(as a string), it can push alert & update alert.*/

class Module
{
public string location;
public Boolean alert;
public string notification,
void sendAlert()
{
if(alert)
{
Console.WriteLIne("Alert:"+notification+"Agent in "+this.location);
}
}
}

Step 2: Set up the observer and subject abstractions
The abstractions for observer and subject will be interface.

/*All observer classes implement an observer interface, it can update object data based
on subjects. Observer classes may need a list of subject to access*/
interface IObserver
{
void update();
}

/*All subject classes implement a subject interface, it can notify observer, add/remove
observer in its update list. Subject classes also need a list of observer to update*/
interface ISubject
{
void NotifyObserver();
void AddObject(IObserver obj);
void RemoveObject(IObserver obj);
}

Step 3: Modify our subject class via implement ISubject interface
class Terrorist : ISubject
{
public string location;
private List obs = new List();
public void NotifyObserver()
{
foreach (var o in obs)
{
o.update(this);
}
}

public void AddObject(IObserver obj)
{
obs.Add(obj);
}

public void RemoveObject(IObserver obj)
{
obs.Remove(obj);
}
}

Step 4: Modify our observer class via implement IObserver interface
class Module : IObserver
{
public string notification;
public Boolean alert;
public string location;
public void update(Terrorist t)
{
if (this.location == t.location)
{
this.alert = true;
this.notification = "Terrorist Nearby ";
}
else
{
this.alert = false;
this.notification = "";
}
SendAlert();
}
void SendAlert()
{
if (alert)
{
Console.WriteLine("Alert: " + notification + "Agent in " + this.location);
}
}
}

Step 5: Finally run the code
namespace d2cObserverDesignPatternSample
{
class Program
{
static void Main(string[] args)
{
//create all data objects
Terrorist t = new Terrorist();
Module m1 = new Module();
Module m2 = new Module();
Module m3 = new Module();
//Add observer
t.addObs(m1);
t.addObs(m2);
t.addObs(m3);
//create all location
string[] locs = new string[5];
locs[0] = "New Delhi";
locs[1] = "Kolkata";
locs[2] = "Mumbai";
locs[3] = "Punjab";
locs[4] = "Pune";
// Set observer to their location
m1.location = locs[1];
m2.location = locs[3];
m3.location = locs[4];
//As the terrorit relocates all over India, it will notify all device modules of its location.
//Module will trigger when a terrorist is nearby
for (int i = 0; i < 5; i++)
{
t.location = locs[i];
t.notifyObservers();
}
Console.ReadLine();
}
}
}

Output
Alert: Terrorist Nearby Agent in Kolkata
Alert: Terrorist Nearby Agent in Punjab
Alert: Terrorist Nearby Agent in Pune

multicast delegate

Multicast Delegate

  • A Multicast delegate is delegate which has references to more than one function.
  • When we invoke a multicast delegate, all function the delegate is pointing to, are invoked.
  • A multicast delegate, invoke the methods in same order in which they are added.
  • We can register a method with a delegate using + OR += operator.
  • We can un-register a method with from a delegate using – OR -= operator.

Example:

namespace d2cMulticastDelegateSample
{
class Program
{
public delegate void d2cDelegateObj();
static void Main(string[] args)
{
d2cDelegateObj delObj1 = new d2cDelegateObj(d2cMethodOne);
d2cDelegateObj delObj2 = new d2cDelegateObj(d2cMethodTwo);
d2cDelegateObj delObj3 = new d2cDelegateObj(d2cMethodThree);
d2cDelegateObj delObj4;

//register delegate using + operator
delObj4 = delObj3 + delObj1 + delObj2;// register a method with a delegate
Console.WriteLine("Multicast Delegate after register method with + operator");
delObj4();
// invoke the methods in same order in which they are added
Console.WriteLine("\n\nMulticast Delegate after un-register method with -= operator");
delObj4 -= delObj2;
delObj4();
Console.ReadLine();
}

public static void d2cMethodOne()
{
Console.WriteLine("Method One, Welcome to desire2code.com ");
}
public static void d2cMethodTwo()
{
Console.WriteLine("Method Two, Welcome to desire2code.com ");
}
public static void d2cMethodThree()
{
Console.WriteLine("Method Three, Welcome to desire2code.com ");
}
}
}

Output:

Multicast Delegate after register methos with + operator
Method Three, Welcome to desire2code.com
Method One, Welcome to desire2code.com
Method Two, Welcome to desire2code.com

Multicast Delegate after un-register methos with -= operator
Method Three, Welcome to desire2code.com
Method One, Welcome to desire2code.com

  • A delegate has a return type other than void, and if the delegate is a multicast delegate, only the value of the last invoked method will be returned.

Example:

public delegate string d2cDelegateObj();
static void Main(string[] args)
{
d2cDelegateObj delObj1 = new d2cDelegateObj(d2cMethodOne);
d2cDelegateObj delObj2 = new d2cDelegateObj(d2cMethodTwo);
d2cDelegateObj delObj3 = new d2cDelegateObj(d2cMethodThree);
d2cDelegateObj delObj4;

//register delegate using + operator
delObj4 = delObj3 + delObj1 + delObj2; // register a method with a delegate
Console.WriteLine("Multicast Delegate after register method with + operator");
Console.WriteLine(delObj4());
// Because delObj2 added at last so this multicast delegate invoked function and return delObj2 return value
Console.ReadLine();
}

public static string d2cMethodOne()
{
return "Method One";
}
public static string d2cMethodTwo()
{
return "Method Two";
}
public static string d2cMethodThree()
{
return "Method Three";
}

Output:

Multicast Delegate after register method with + operator
Method Two

Basics of delegate

What is delegate

  • A delegate is a type safe function pointer.
  • Delegate hold a reference to a function.
  • The signature of the delegate must match the signature of the function, the delegate points to,otherwise we get a compiler error.This is the reason delegates as called type safe function pointers.
  • A delegate is similar to a class, we can create an instance of it, and when we do so, we pass in the function as parameter to the delegate, constructor, and it is to this function the delegate will point to.

Example

using System;
namespace d2cDelegatesSample
{
class Program
{
public delegate void WelcomeWindowDelegate(string inputMeggage);

static void Main(string[] args)
{
WelcomeWindowDelegate objDelegate = new WelcomeWindowDelegate(WelcomeWindow);
objDelegate("Welcome To Desire2Code.com");
}

public static void WelcomeWindow(string inputMessage)
{
Console.WriteLine(inputMessage);
Console.ReadLine();
}
}
}

C# Multithreading interview questions with answers Part 1

What is the difference between Process and Thread?

  • A process is what the operating system uses to facilitate the execution of a program by providing the resources required.
  • A process can start multiple threads.
  • Every process is start with a single thread called primary thread.
  • A single process can have multiple threads.
  • Threads share the resources allocated to process.
  • A process is the parent and threads are his children.

How to create and start a Thread in C#?

We have to use the Thread class provided by System.Threading namespace. In the constructor of the class, we have to pass the method name which we want to run in separate thread. After than we have to call the start method of Thread class. Below is the example.

using System;
using System.Threading;

namespace d2cThreadSample
{
class Program
{
static void Main(string[] args)
{
Thread objThread1 = new Thread(d2cThreadMethod);
objThread1.Start();
}

private static void d2cThreadMethod()
{
Console.WriteLine("Welcome to desire2code.com");
Console.ReadLine();
}

}
}

How to pass parameter in Thread?

In the constructor of Thread, we can pass the method name which accepts only a single parameter. Then we have to pass parameter into the Start method. Below is the example.
using System;
using System.Threading;

namespace d2cThreadSample
{
class Program
{
static void Main(string[] args)
{
Thread objThread1 = new Thread(d2cThreadMethod);
objThread1.Start("Welcome to desire2code.com");
}

private static void d2cThreadMethod(object inputString)
{
Console.WriteLine(inputString);
Console.ReadLine();
}

}
}

What is Deadlock? What are four necessary conditions for Deadlock?

A deadlock is a situation in which two or more processes cannot complete their work.They are blocked and each thread waiting for other threads to release resource they want. For example, we have two threads T1 and T2 and we have two resources R1 and R2. Both threads want to work with both resources. But in opposite fashion, T1 want to work with R1 first and then with R2. T2 want to work with R2 first and then with R1. Both threads starts at the same time. T1 locked R1 while at the same time T2 locked R2. Now T1 want a lock on R2 which is already locked by T2 and T2 want a lock on R1 which is already locked by T1. Both threads waiting for other threads to unlock the resources. Both threads are waiting for infinite time and cann’t continue forever.

deadlock

Deadlock Conditions
mutual exclusion
The resources involved must be unshareable; otherwise, the processes would not be prevented from using the resource when necessary.
hold and wait or partial allocation
The processes must hold the resources they have already been allocated while waiting for other (requested) resources. If the process had to release its resources when a new resource or resources were requested, deadlock could not occur because the process would not prevent others from using resources that it controlled.
no pre-emption
The processes must not have resources taken away while that resource is being used. Otherwise, deadlock could not occur since the operating system could simply take enough resources from running processes to enable any process to finish.
resource waiting or circular wait
A circular chain of processes, with each process holding resources which are currently being requested by the next process in the chain, cannot exist. If it does, the cycle theorem (which states that “a cycle in the resource graph is necessary for deadlock to occur”) indicated that deadlock could occur.

What is immutable object? How to create an immutable object?

An immutable object is an object which states cannot be changed after creation. Immutable objects are useful in concurrent programming as they are thread-safe. Immutable objects are objects which once loaded cannot be changed / modified by any way external or internal.

Immutable objects can be created only from immutable classes. To create an immutable class is a three step process:

Step 1: Remove the setters of the class, only have getters.

class ImmutableObject
{
private string _applicationSessionId;
public string applicationSessionId
{
get { return _applicationSessionId; }
}
}

Step 2: Provide parameters via constructor.

class ImmutableObject
{
private string _applicationSessionId;
public string applicationSessionId
{
get { return _applicationSessionId; }
}
public ImmutableObject(string iapplicationSessionId)
{
_applicationSessionId = iapplicationSessionId;
}
}

Step 3: Make the variables of the property READONLY

class ImmutableObject
{
private readonly string _applicationSessionId;
public string applicationSessionId
{
get { return _applicationSessionId; }
}
ImmutableObject(string iapplicationSessionId)
{
_applicationSessionId = iapplicationSessionId;
}
}

top 5 c# interview question with answer

1. What is Managed or Unmanaged Code?

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

2. What is Boxing and Unboxing?
Boxing and Unboxing both are used for type conversion but have some difference:

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.

Example:
private void boxing()
{
int _iLocal = 170;
object _obj = _iLocal;//boxing
Console.WriteLine(_obj);
}

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.

Example:
private void unboxing()
{
object _obj = 170;
int _iLocal = (int)_obj;//unboxing
Console.WriteLine(_iLocal);
}

3. What is the difference between a struct and a class in C#?

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

Struct 

  • The struct is value type in C# and it inherits from System.Value Type.
  • Struct is usually used for smaller amounts of data.
  • Struct can’t be inherited to other type.
  • A structure can’t be abstract.
  • No need to create object by new keyword.
  • Do not have permission to create any default constructor.

Class

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

4. What is the difference between Interface and Abstract Class?

Their 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.
  • 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 declare or use any variables while an interface is not allowed to do so.
  • 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 use constructor while in an interface we don’t have any type of constructor
  • 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.
  • An abstract class can’t be used for multiple inheritance while interface can be used as multiple inheritance.

5.What is the difference between string and StringBuilder in c#?
StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance:

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

private void stringFun()
{
string str = string.Empty;
str += "Welcome";// creata a new string instance rather then using old one
str += " to desire2code.com";
Console.WriteLine(str);
}

Point to remember:

  • It’s an immutable object that hold string value.
  • Performance wise string is slow because it’s create a new instance to override or change the previous value.
  • String belongs to System namespace.

Stringbuilder is mutable object which also hold 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 existing string with insert functions also replace or append without creating new instance of System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare than System.String. Let’s have an example to understand System.Text.Stringbuilder like:

private void stringBuilderFun()
{
StringBuilder str = new StringBuilder("");
str.Append("Welcome");// Will use it's old instance
str.Append(" to desire2code.com");
Console.WriteLine(str);
}

Point to remember:

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

create and run a console application

To create and run a console application

  • Start Visual Studio.
  • On the menu bar, choose File, New, Project.
  • The New Project dialog box opens.
  • Expand Installed, expand Templates, expand Visual C#, and then choose Console Application.
  • The new project appears in Solution Explorer.
  • If Program.cs isn’t open in the Code Editor, open the shortcut menu for Program.cs in Solution Explorer, and then choose View Code.
  • Replace the contents of Program.cs with the following code.


// “Welcome 2 Desire2Code.com” program in C#.
using System;
namespace Desire2Code
{
class Welcome
{
static void Main()
{
Console.WriteLine(“Welcome 2 Desire2Code.com”);
// Keep the console window open in debug mode.
Console.WriteLine(“Press any key to exit.”);
Console.ReadKey();
}
}
}

Choose the F5 key to run the project. A Command Prompt window appears that contains the line Welcome 2 Desire2Code.com