Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, February 3, 2015

ref and out in c#.net

Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Program with ref and out keyword


public class Example
{
 public static void Main() //calling method
 {
 int val1 = 0; //must be initialized 
 int val2; //optional
 Example1(ref val1);
 Console.WriteLine(val1); // val1=1
 Example2(out val2);
 Console.WriteLine(val2); // val2=2
 }
 static void Example1(ref int value) //called method
 {
 value = 1;
 }
 static void Example2(out int value) //called method
 {
 value = 2; //must be initialized 
 }
}

Ref and out in method overloading


Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time. Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.

class MyClass
{
 public void Method(out int a) // compiler error “cannot define overloaded”
 {
 // method that differ only on ref and out"
 }
 public void Method(ref int a) 
 {
 // method that differ only on ref and out" 
 }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
 public void Method(int a) 
 {
 }
 public void Method(out int a)
 {
 // method differ in signature.
 }
}

Monday, February 2, 2015

Action and Func Delegates in C# .NET

The Func and Action generic delegates were introduced in the .NET Framework version 3.5.

Whenever we want to use delegates in our examples or applications, typically we use the following procedure:

  1. Define a custom delegate that matches the format of the method.
  2. Create an instance of a delegate and point it to a method.
  3. Invoke the method.
  4. But, using these 2 Generics delegates we can simply eliminate the above procedure.
  5. Since both the delegates are generic, you will need to specify the underlaying types of each parameters as well while pointing it to a function.

 For example Action<type,type,type……>

Action<>


  • The Generic Action<> delegate is defined in the System namespace of microlib.dll
  • This Action<> generic delegate, points to a method that takes up to 16 Parameters and returns void.


Func<>


  • The generic Func<> delegate is used when we want to point to a method that returns a value.
  • This delegate can point to a method that takes up to 16 Parameters and returns a value.
  • Always remember that the final parameter of Func<> is always the return value of the method. (For examle Func< int, int, string>, this version of the Func<> delegate will take 2 int parameters and returns a string value.)

Let's look at an example to see the use of both Delegates.

Create a new project named “FuncAndActionDelegates” and create a new class that holds all your methods.

MethodCollections.cs

class MethodCollections  
    {  
  
        //Methods that takes parameters but returns nothing:  
   
        public static void PrintText()  
        {  
            Console.WriteLine("Text Printed with the help of Action");  
        }  
        public static void PrintNumbers(int start, int target)  
        {  
            for (int i = start; i <= target; i++)  
            {  
                Console.Write(" {0}",i);  
            }  
            Console.WriteLine();  
        }  
        public static void Print(string message)  
        {  
            Console.WriteLine(message);  
        }  
  
        //Methods that takes parameters and returns a value:  
  
        public static int Addition(int a, int b)  
        {  
            return a + b;  
        }  
  
        public static string DisplayAddition(int a, int b)  
        {  
            return string.Format("Addition of {0} and {1} is {2}",a,b,a+b);  
        }  
  
        public static string SHowCompleteName(string firstName, string lastName)  
        {  
            return string.Format("Your Name is {0} {1}",firstName,lastName);  
        }  
        public static int ShowNumber()  
        {  
            Random r = new Random();  
            return r.Next();  
        }  
    }  


Program.cs

class Program  
    {  
        static void Main(string[] args)  
        {  
            Action printText = new Action(MethodCollections.PrintText);  
            Action<string> print = new Action<string>(MethodCollections.Print);  
            Action<int, int> printNumber = new Action<int, int>(MethodCollections.PrintNumbers);  
  
            Func<int, int,int> add1 = new Func<int, int, int>(MethodCollections.Addition);  
            Func<int, int, string> add2 = new Func<int, int, string>(MethodCollections.DisplayAddition);  
            Func<string, string, string> completeName = new Func<string, string, string>(MethodCollections.SHowCompleteName);  
            Func<int> random = new Func<int>(MethodCollections.ShowNumber);  
  
            Console.WriteLine("\n***************** Action<> Delegate Methods ***************\n");  
            printText();    //Parameter: 0 , Returns: nothing  
            print("Abhishek");  //Parameter: 1 , Returns: nothing  
            printNumber(5, 20); //Parameter: 2 , Returns: nothing  
            Console.WriteLine();  
            Console.WriteLine("**************** Func<> Delegate Methods *****************\n");  
            int addition = add1(2, 5);  //Parameter: 2 , Returns: int  
            string addition2 = add2(5, 8);  //Parameter: 2 , Returns: string  
            string name = completeName("Abhishek", "Yadav");    //Parameter:2 , Returns: string  
            int randomNumbers = random();   ////Parameter: 0 , Returns: int  
  
            Console.WriteLine("Addition: {0}",addition);  
            Console.WriteLine(addition2);  
            Console.WriteLine(name);  
            Console.WriteLine("Random Number is: {0}",randomNumbers);  
  
            Console.ReadLine();  
        }  

    }  

Output :

Friday, January 30, 2015

S.O.L.I.D Architecture principle in C# (Part 5)

Continue to Thursday, January 29, 2015
------------------------------------------------------

Dependency Inversion Principle (DIP)


Dependency Inversion Principle or DIP states that:

High-level modules should not depend on low-level modules. Both should depend on abstractions. 
Abstractions should not depend on details. Details should depend on abstractions.

Consider that you are developing an application that deals with user management (creating a user, managing their passwords, etc.). After every user management task you wish to send a notification to the user as well as to the administrator about the activity performed. The following code shows a simplified implementation of this system.

public class EmailNotifier
{
    public void Notify(string email, string message)
    {
        //send email here
    }
}

public class UserManager
{
    EmailNotifier notifier = new EmailNotifier();

    public void CreateUser(string userid,string password,string email)
    {
        //create user here
        notifier.Notify(email, "User created successfully!");
    }

    public void ChangePassword(string userid, string oldpassword,string newpassword)
    {
        //change password here
        notifier.Notify(email, "Password changed successfully");
    }
}
The EmailNotifier class has just one method - Notify() that accepts an email address and a notification message. Inside, it sends an email to the specified address notifying the user of the change. The UserManager class declares an instance of EmailNotifier class and uses it in methods such as CreateUser() and ChangePassword(). So far so good. Now assume that instead of email notification you want to send SMS based notifications. To cater to this change you not only need to write another class (say SMSNotifier) but also need to change UserManager class because UserManager uses EmailNotifier. This problem arises due to the fact that high level module UserManager depends on a concrete low level module EmailNotifier.

Let's change our classes to follow DIP.

public abstract class NotifierBase
{
    public abstract void Notify(string message);
}

public class EmailNotifier:NotifierBase
{
    public string EmailAddress { get; set; }
    public override void Notify(string message)
    {
        //send email here
    }
}

public class SMSNotifier : NotifierBase
{
    public string MobileNumber { get; set; }
    public override void Notify(string message)
    {
        //send SMS here
    }
}

public class UserManager
{
    public NotifierBase Notifier { get; set; } 

    public void CreateUser(string userid,string password,string email)
    {
        //create user here
        Notifier.Notify("User created successfully!");
    }

    public void ChangePassword(string userid, string oldpassword,string newpassword)
    {
        //change password here
        Notifier.Notify("Password changed successfully");
    }
}
Now, the code defines an abstract class NotifierBase that defines the Notify() method. The two classes EmailNotifier and SMSNotifier inherit from the NotifierBase class and provide the necessary implementation details. More importantly the UserManager class no longer uses a specific concrete implementation. It uses a NotifierBase abstraction in the form of the Notifier public property. This public property can be set by the consumer of the UserManager class either to an instance of EmailNotifier class or to an instance of SMSNotifier class or any other class that inherits from NotifierBase class. Thus our code now depends on abstractions and not on the concrete implementation.

Summary

SOLID principles of object oriented programming allow you to write structured and neat code that is easy to extend and maintain. SOLID principles include Single Responsibility Principle (SRP), Open/Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP) and Dependency Inversion Principle (DIP).


Thursday, January 29, 2015

S.O.L.I.D Architecture principle in C# (Part 4)

Continue to Wednesday, January 28, 2015

-----------------------------------------------------

Interface Segregation Principle (ISP)


Interface Segregation Principle or ISP states that:

No client should be forced to depend on methods it does not use. 
Many client-specific interfaces are better than one general-purpose interface.

What does that mean? Let's take an example. Suppose you are building an order processing system that accepts orders from the customers and places them in the system for dispatch and further processing. The orders can be accepted through various channels such as an ecommerce website, telephone and cash on delivery. To deal with this kind of processing you created the following abstract class:

public abstract class OrderProcessor
{
    public abstract bool ValidatePaymentInfo();
    public abstract bool ValidateShippingAddress();
    public abstract void ProcessOrder();
}

The OrderProcessor class has three methods ValidatePaymentInfo(), ValidateShippingAddress() and ProcessOrder(). The ValidatePaymentInfo() method is supposed to validate the credit card information and return true if the information is correct. The ValidateShippingAddress() method is supposed to check whether the address is reachable by the available means of transport and if so return true. Finally, the ProcessOrder() will place an order into the system.

Now, assume that you created two concrete implementations of OrderProcessor as shown below:

public class OnlineOrder:OrderProcessor
{

    public override bool ValidatePaymentInfo()
    {
        return true;
    }

    public override bool ValidateShippingAddress()
    {
        return true;
    }

    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

public class CashOnDeliveryOrder:OrderProcessor
{

    public override bool ValidatePaymentInfo()
    {
        throw new NotImplementedException();
    }

    public override bool ValidateShippingAddress()
    {
        throw new NotImplementedException();
    }

    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

The OnlineOrder class is supposed to be used by some ecommerce application that accepts payments through credit cards. The CashOnDeliveryOrder class is supposed to serve cash on delivery orders. These orders won't accept any credit card payments. They accept only cash payments. Can you see the problem there? The two methods ValidatePaymentInfo() and ValidateShippingAddress() throw NotImplementedException because CashOnDeliverOrder doesn't need these methods. However, since the OrderProcessor class provides a general purpose interface the CashOnDeliveryOrder class is forced to write these methods. Thus ISP is being violated in this example.

Now let's fix the problem. The following code shows the corrected version of the classes:

public abstract class OrderProcessor
{
    public abstract void ProcessOrder();
}

public abstract class OnlineOrderProcessor
{
    public abstract bool ValidatePaymentInfo();
    public abstract bool ValidateShippingAddress();
    public abstract void ProcessOrder();
}
public class ECommerceOrder : OnlineOrderProcessor
{

    public override bool ValidatePaymentInfo()
    {
        return true;
    }

    public override bool ValidateShippingAddress()
    {
        return true;
    }

    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

public class CashOnDeliveryOrder : OrderProcessor
{
    public override void ProcessOrder()
    {
        //place order here if everything is ok.
    }
}

The above code defines two abstract classes OrderProcessor and OnlineOrderProcessor. The OrderProcessor has only one method, ProcessOrder() whereas OnlineOrderProcessor has three methods - ValidatePaymentInfo(), ValidateShippingAddress() and ProcessOrder(). The ECommerceOrder class inherits from OnlineOrderProcessor and the CashOnDeliveryOrder class inherits from OrderProcessor. Since OrderProcessor doesn't contain the ValidatePaymentInfo() and ValidateShippingAddress() CashOnDelivery need not write them at all. Thus we created multiple client specific interfaces (OrderProcessor and OnlineOrderProcessor) instead of a generic one.

Wednesday, January 28, 2015

S.O.L.I.D Architecture principle in C# (Part 3)

Continue to Tuesday, January 27, 2015
----------------------------------------------

Liskov Substitution Principle (LSP) :


Liskov Substitution Principle or LSP states that:

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

You must be aware that you can use an object of a derived class anywhere where base class is expected. However, when such a substitution occurs the functionality and correctness of the code shouldn't change. Let's understand this with an example. Suppose you have created a class named SpecialCustomers that maintains a list of special Customers (may be they are special because they are frequent buyers, or they purchase high value items). This class is shown below:

public class SpecialCustomers
{
    List<Customer> list = new List<Customer>();
 
    public virtual void AddCustomer(Customer obj)
    {
        list.Add(obj);
    }
 
    public int Count
    {
        get
        {
            return list.Count;
        }
    }
}

The SpecialCustomers class maintains a List of Customer instances (Customer class is not shown in the code for the sake of simplicity). The AddCustomer() method accepts an instance of Customer and adds to the generic List. The Count property returns the number of Customer elements in the List.

Now, let's assume that you create another class - TopNCustomers - that inherits from the SpecialCustomers class. This class is shown below:

public class TopNCustomers:SpecialCustomers
{
    private int maxCount = 5;
 
    public override void AddCustomer(Customer obj)
    {
        if (Count < maxCount)
        {
            AddCustomer(obj);
        }
        else
        {
            throw new Exception("Only " + maxCount + " customers can be added.");
        }
    }
}

The TopNCustomers class overrides the AddCustomer() method of the SpecialCustomers base class. The new implementation checks whether the customer count is less than maxCount (5 in this case). If so, the Customer is added to the List else an exception is thrown.

Now, have a look at the following code that uses both of these classes.

SpecialCustomers sc = null;
sc = new TopNCustomers();
for (int i = 0; i < 10; i++)
{
    Customer obj = new Customer();
    sc.AddCustomer(obj);
}

The code declares a variable of type SpecialCustomers and then points it to an instance of TopNCustomers. This assignment is perfectly valid since TopNCustomers is derived from SpecialCustomers. The problem comes in the for loop. The for loop that follows attempts to add 10 Customer instances to the TopNCustomers. But TopNCustomers allows only 5 instances and hence throws an error. If sc would have been of type SpecialCustomers the for loop would have successfully added 10 instances into the List. However, since the code substitutes TopNCustomers instance in place of SpecialCustomers the code produces an exception. Thus LSP is violated in this example.

To rectify the problem we will rewrite the code like this:

public abstract class CustomerCollection
{
    public abstract void AddCustomer(Customer obj);
    public abstract int Count { get; }
}
 
public class SpecialCustomers:CustomerCollection
{
    List<Customer> list = new List<Customer>();
 
    public override void AddCustomer(Customer obj)
    {
        list.Add(obj);
    }
 
    public override int Count
    {
        get
        {
            return list.Count;
        }
    }
}
 
public class TopNCustomers : CustomerCollection
{
    private int count=0;
    Customer[] list = new Customer[5];
 
    public override void AddCustomer(Customer obj)
    {
        if(count<5)
        {
            list[count] = obj;
            count++;
        }
        else
        {
            throw new Exception("Only " + count + " customers can be added.");
        }
    }
 
    public override int Count
    {
        get
        {
            return list.Length;
        }
    }
}

Now, the code has CustomerCollection abstract class with one property (Count) and one method (AddCustomer). The SpecialCustomers and TopNCustomers classes inherit from this abstract class and provide the concrete implementation for the Count and AddCustomer(). Notice that in this case TopNCustomers doesn't inherit from SpecialCustomers.

The new set of classes can then be used as follows:

Customer c = new Customer() { CustomerID = "ALFKI" };
CustomerCollection collection = null;
collection = new SpecialCustomers();
collection.AddCustomer(c);
collection = new TopNCustomers();
collection.AddCustomer(c);

The above code declares a variable of CustomerCollection type. Once it points to an instance of SpecialCustomers and then to TopNCustomers. In this case, however, their base class is CustomerCollection and the instances are perfectly substitutable for it without producing any inaccuracies.