Search This Blog

Thursday, October 24, 2013

Factory Design Pattern C#

C# > Design Patterns > Factory

The factory completely abstracts the creation and initialization of the product from the client.

This indirection enables the client to focus on its role in the application without concerning itself with the details of how the product is created.

In this way the product implementation changes over time and the client remains unchanged.

Model:

Client -> (uses) -> Factory -> (creates) - > Product

 

Example:

Database factory class

                public enum DbOptions
        {
            SQLServer,
            Oracle
        }

        public interface IDatabase
        {
            string Connect();
        }

        public class clsSQlServer : IDatabase
        {
            public string Connect()
            {
                return ("You connected to SQlServer");
            }
        }
        public class clsOracle : IDatabase
        {
            public string Connect()
            {
                return ("You connected to Oracle");
            }
        }
        public class clsUnknown : IDatabase
        {
            public string Connect()
            {
                return ("Unknown database");
            }
        }

        public class DatabaseChoice // Factory class
        {
            static public IDatabase getDBObj(DbOptions db)

            {
                IDatabase objDb = null;
                if (db == DbOptions.SQLServer)
                {
                    objDb = new clsSQlServer();
                }
                else if (db == DbOptions.Oracle)
                {
                    objDb = new clsOracle();
                }

                // In the future if will use MySql only add here
                //else if (db == DbOptions.MySql)
                //{
                //    objDb = new clsMySql();
                //}
                else
                {
                    objDb = new clsUnknown();
                }
                return objDb;
            }
         }
// client

IDatabase objDb = DatabaseChoice.getDBObj(DbOptions.Oracle);
MessageBox.Show(objDb.Connect());

     





Wednesday, October 23, 2013

Events in C#

An event is a message sent by an object to signal the occurrence of an action.
An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.
The most use for events is in graphical user interfaces and the action could be caused by user interaction or it could be triggered by some other program logic.

Example:

// Declare a delegate for an event. 
delegate void EventHandler();

class Product
{
public string Name { get; set; }
       private int mQuantity;
       public int Quantity
       {
            get
            {
                  return mQuantity;
             }
             set
             {
                    mQuantity = value;
                    OnQuantityChange();
              }
       }

      // Declare event. 
       public event EventHandler QuantityChangeEvent;

       // This is called to fire the event.
       public void OnQuantityChange()
       {
              if (QuantityChangeEvent != null)
                     QuantityChangeEvent();
             }
}

 
static void handler()
{
      MessageBox.Show("Quantity changed!"); 
}

Product p = new Product();

//Add handler() to the event list.
p.QuantityChangeEvent += new EventHandler(handler);
p.Name = "Prod A";
p.Quantity = 10;
p.Quantity = 0;

<< Anonymous functions






Anonymous Functions in C#

An anonymous function is an inline statement or expression that can be used wherever a delegate type is expected.
An anonymous function has no name.

Types of anonymous functions:
  • Lambda Expressions
  • Anonymous Methods
Example:

delegate void TestAnonymousFunctionDelegate(string s);


// A delegate can be initialized with inline code - anonymous method
TestAnonymousFunctionDelegate del1 = delegate(string s) { MessageBox.Show(s); };
del1("This is anonymous method.");

// A delegate can be initialized with a lambda expression.
TestAnonymousFunctionDelegate del2 = (x) => { MessageBox.Show(x); };
del2("This is lambda expression.");

 
<< Multicast delegates                                                                                              Events >>





Mulicast delegate in C#

C# > Delegate

Mulicast delegate is a delegate that can have more than one element in its invocation list.

Example

public delegate void MultiDelegate(int x,int y);
private class Operator
{
            public void Add(int x, int y)
       {
              MessageBox.Show ("The sum is: " + (x + y));
       }
       public void Sub(int x, int y)
       {
              MessageBox.Show("The sub is: " + (x - y));
       }
}

MultiDelegate ptr=null;
//add more than one function called multicast delegate.
ptr += new MultiDelegate(obj.Add);
ptr += new MultiDelegate(obj.Sub);
ptr(50, 10);

<< Delegates                                                                                  Anonymous functions >>





Delegates in c#

C# > Delegate

A delegate in C# is similar to a function pointer in C++. This allows encapsulating a reference to a method inside a delegate object.
A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance.

An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references
Delegates are especially used for implementing events and the call-back methods.

1. Basic delegate example

// declaration

        private delegate void TestDelegate();

        private  void StartTestDelegate()
        {
            MessageBox.Show("StartTestDelegate"); 
        }
        private void StopTestDelegate()
        {
            MessageBox.Show("StopTestDelegate");
        }

// Instantiation
        TestDelegate del1 = new TestDelegate(StartTestDelegate);
        TestDelegate del2 = new TestDelegate(StopTestDelegate);

// Invocation
        del1();
        del2();

2. Math Operator delegate example

  private class Math
  {
            public int Add(int x, int y)
            {
                return x + y;
            }
            public int Sub(int x, int y)
            {
                return x - y;
            }
            public MathDelegate Operator(int op) 
            {
                MathDelegate objDelegateMath = null;  // delegate reference
                if (op == 1)
                    objDelegateMath = Add;  // point the reference to methods
                else
                    objDelegateMath = Sub;  // point the reference to methods
               return objDelegateMath; 
            }
  }

  Math objMath = new Math();
  //Invoke the methods through delegate
  MessageBox.Show(objMath.Operator(1).Invoke(1, 2).ToString());
  MessageBox.Show(objMath.Operator(2).Invoke(5, 4).ToString()); 

3. Logger class delegate example 

Multicast delegates >>






Tuesday, October 22, 2013

Switch statement C#

C# > Statements > switch

Switch selects a switch section to execute from a list of values

Switch expression: numeric, char, enum or string.
Every statement sequence in a case must be terminated with:
  • break 
  • return
  • goto
  • throw
If no case label matches default.
If no default specified continuation after the switch statement.

Example:

  private void TestSwitch(int a)
        {
            int b = 0;
            switch (a)
            {
                case 1:
                    b += 1;
                    break;
                case 2:
                    b += 1;
                    goto case 1;
                case 3:
                    return;
                default:
                   MessageBox.Show("Invalid selection.");
                   break;
            }
        }