Showing posts with label C# tutorial. Show all posts
Showing posts with label C# tutorial. Show all posts

13 September 2015

avoiding the execution of finally block of code in C# .NET

We all know that finally block of code is always going to get executed irrespective of whether there is an exception or not. Thereby finally() block of code helps to clean any resources held up by the code.

But, there is one exception to the above rule.

The finally block of code will not get executed, when the code executes Environment.FailFast() method.

static void Main(string[] args)
{       
  try
  {
    Environment.FailFast("Message logged!");
  }
  catch (Exception ex)
  {
                    
  }
  finally
  {
    Console.WriteLine("finally executed...");
  }
}

Whenever Environment.FailFast() method gets executed, it immediately terminates a process after it writes the message to the Windows Application Event log!

You can see the below error logged into Windows Application log.

Application: FailFast.exe Framework Version: v4.0.30319 Description: The application requested process termination through System.Environment.FailFast(string message). Message: Message logged! Stack: at System.Environment.FailFast(System.String) at FailFast.Program.Main(System.String[])

24 May 2015

why and when to use IComparer

Assume for a while you are developing an e-commerce site which allows customers to sort the products in ascending, descending order of price and product title. And if sorting options aren't provided by your products data provider, then you have to implement sorting logic in C# .NET code.

To implement sorting you could think of System.IComparable interface. Your Product entity class can implement IComparable interface CompareTo() method. Inside the CompareTo() method, you can have logic to meet one kind of products sorting requirement. But requirement is, products should be displayed based on multiple sorting options.

So when there is a need for such multiple sort order requirement, IComparer interface will come to your rescue. Let's first have look at definition of IComparer interface.

public interface IComparer 
{
   int Compare(T x, T y);
}
  • IComparer interface has a method called Compare() and it's accepting two parameters of type T.
  • The Compare() method returns a integer value. The return value will be zero when if both x and y are equal, +1 if X > Y else its -1.

Enough of theory, let's implement a Comparer for product to sort products based on product name ascending order.

public class ProductNameComparer:IComparer
 {
   public int Compare(Product x, Product y)
     {
       return x.Name.CompareTo(y.Name);
     }
 }

Similarly you can implement another product comparer to sort products based on their price descending order.

public class ProductPriceComparer:
     IComparer<Product>
 {
   public int Compare(Product x, Product y)
    {
      return y.Price.CompareTo(x.Price);
    }
 }

Now let's see usage of our custom comparer classes implementing IComparer interface.

List<Product> products = new List<Product>();
products.Add(new Product() { 
           Name="Cell phone", Price=2});

  products.Add(new Product() { 
           Name = "Laptop", Price = 3 });

products.Add(new Product() { 
           Name = "Apple Fruit", Price = 1 });

Let's see how to sort product based on their price descending order using the comparer. List class has Sort method which accepts the IComparer implementation. Below is the code listing for the same.

//sort the products by their price
products.Sort(new ProductPriceComparer());

After the above sorting code executed, products will be sorted based on their price in descending order.

Name: Laptop & Price: 3
Name: Cell phone & Price: 2
Name: Apple Fruit & Price: 1

Similarly you can use ProductNameComparer to sort products based on their name in ascending order.

//sort the products by their price
products.Sort(new ProductPriceComparer());

After the above sorting code executed, products will be sorted based on their price in descending order.

Name: Apple Fruit & Price: 1
Name: Cell phone & Price: 2
Name: Laptop & Price: 3

29 March 2015

difference between events and delegates

Events and delegates are very important programming design concepts when you start doing your low-level design and class level diagrams. So it's very crucial to understand what each of them and very important to understand the difference between them. In this post let's try to understand difference between events and delegates.

If you look patiently at events and delegates you will realize with both events and delegates you can add matching methods to them and upon on invoking either of a delegate or an event, the respective methods will be get called. So then what is the difference between events and delegates?

You are thinking now!.. don't worry soon you will understand difference.. continue reading...

#1 difference between events and delegates

EVENTS can only be raised from the class in which they have defined whereas your delegates don't have such restriction. DELEGATES can be invoked from both inside the class in which they defined and also from outside as well.

So now the point is, if you want to protect invocation of subscribed methods, you will choose events so that no one attempts directly to raise an event from outside the class. If this is not what you are looking at them consider delegates.

#2 difference between events and delegates

WITH EVENTS you cannot assign altogether a difference value to it, you can only add or remove subscription method to it. Let's consider an example, BalanceChanged event is declared the below class.

public class BankAccount{
public event BalanceChangedEventHandler BalanceChanged;
}
Code Listing A
BankAccount account = new BankAccount();

// INVALID assignment to event
// you can't assign 'null' to event
account.BalanceChanged = null

// INVALID assignment to event
// you can't directly assign event subscription 
// method to event 
account.BalanceChanged = BalanceChangedEventHandlingMethod;
Code Listing B
BankAccount account = new BankAccount();

// VALID subscription to event
account.BalanceChanged+=BalanceChangedEventHandlingMethod;

// VALID un subscription to event
account.BalanceChanged-=BalanceChangedEventHandlingMethod;

With events you can add subscription methods or remove subscription methods, you cannot assign null to an event. So Listing B is valid and Listing A is invalid.

With DELEGATES, you can assign null to it and directly assign any method to it apart from subscribing and unsubscribing methods. So even thing in below code listing is valid.

public class BankAccount{
public delegate string GetLanguageLiteralText(string key);
}

BankAccount account = new BankAccount();

// VALID, you can assign 'null' to a delegate.
account.GetLanguageLiteralText = null;

// VALID, you can directly 
// assign a method to a delegate
account.GetLanguageLiteralText = GetResourceTextViaWebservice;

// You can subscribe to delegate and unsubscribe to delegate
account.GetLanguageLiteralText += GetResourceTextViaWebservice;
account.GetLanguageLiteralText -= GetResourceTextViaWebservice

So now I think you aware not just events and delegates but also difference between them and you feel more confident while choosing between an event or a delegates your design.

As always add your comments guys, that will keep me writing blog spots.

14 January 2015

events in c# - explained in detail

Events are an important concept in object-oriented programming (OOPS). In this article let's discuss what are events, how to declare events in C#, when to use events, how to subscribe to an event, etc.

What are events

Events are the mechanism to let know something interesting has occurred. The source entity which raises the event is called as an event raiser. And the entities which are interested in the event are known as event subscribers.

How to declare events in C# language

Its always better to start with an example whenever learning a new thing. Let's consider the below event declared in C#.
public event BalanceChangedEventHandler BalanceChanged;
  • Where event is keyword used to declare events in C#.
  • Event declared is a type BalanceChangedEventHandler delegate. A event will be declared for a specific delegate type. So you need to decide on delegate to be used before declaring an event.
  • Next, you need to give a appropriate name to a event. In this case BalanceChanged is the event name.
  • As always you specify the visibility of a class member using access specifiers.

Why and when to use events

Let's consider you have got BankAccount class. Whenever the account's balance changes you need to let know the consumers of account class about the balance change. In such requirements, you can make use of events.

Events uses a delegate to maintain the list of subscribers. Delegates hold the references of the subscribed event handling methods. But doesn't aware of the classes which have defined events handling methods. That means the class which raises the event doesn't have a direct coupling with the class which has subscribed to the event. So using events makes the classes in the application loosely coupled with each other. This is advantage of using the events and delegates in the application design.

public class BankAccount
{

// Declare delegate
public delegate void BalanceChangedEventHandler
 (object sender, BalanceChangedEventArgs args);

 // Declare event 
 public event BalanceChangedEventHandler BalanceChanged;

 public double _balance;
 public double Balance
  {
    get
    {
      return _balance;
    }
    set
    {
      if (_balance == value)
          return;

      double previousBalance = _balance;
      _balance = value;

       // Raise the event on balance changed
       OnBalanceChanged(previousBalance);
     }
    }
 protected void OnBalanceChanged(double previousBalance)
  {
   // Check if anyone has been subscribed to event
   // If no one has subscribed BalanceChanged will be null
   if (this.BalanceChanged != null)
    {
    BalanceChanged(this
     new BalanceChangedEventArgs(previousBalance, _balance));
    }
  }
}

Let’s dissect above BankAccount class.

  • Declaring a delegate

    public delegate void BalanceChangedEventHandler
    (object sender, BalanceChangedEventArgs args);

    BalanceChangedEventHandler is a delegate matching a method which accepts sender of type object and another argument of type BalanceChangedEventArgs. BalanceChangedEventArgs is a class deriving from EventArgs. EventsArgs will be declared something like below.

    public class BalanceChangedEventArgs:EventArgs
    {
       public decimal PreviousBalance { get; private set; }
       public decimal NewBalance { get; private set; }

       public BalanceChangedEventArgs(decimal previousBalance, 
            decimal newBalance)
       {
          PreviousBalance = previousBalance;
          NewBalance = newBalance;
       }
    }
  • Declaring an event

    BalanceChanged is a event of type BalanceChangedEventHandler delegate. The event will pass the information to subscribers using BalanceChangedEventArgs object.

  • Raising an event

    OnBalanceChanged() method is used to raise an event. Whenever there is a change in the Balance value, the BankAccount class is raising the event. In the event raising method you will check whether anyone has subscribed to a event, if yes then event will be raised by passing in the sender and the event arguments.

    protected void OnBalanceChanged(double previousBalance)
     {
       // Check if anyone has been subscribed to event
       // If no one has subscibed BalanceChanged will be null
       if (this.BalanceChanged != null)
          {
           BalanceChanged(this
               new BalanceChangedEventArgs(previousBalance, _balance));
          }
     }

    Sender is the object raising the event. In this case it is BackAccount object.

    Event argument BalanceChangedEventArgs is used to send new balance and previous balance amount. i.e. Event argument is used to pass event details.

Subscribing to event in C#

We learned about how to declare events and raise events. The whole purpose of the event is to let know some object state has been changed to its subscribers. Now let's see how can we subscribe to events.

In C# language we will subscribe to the event by using overloaded '+' operator. Let's go through an example.

class Program
{
  static void Main(string[] args)
    {
      BankAccount bankAccount = new BankAccount();

       // Subscribe to an event
       bankAccount.BalanceChanged += BankAccount_BalanceChanged;
       bankAccount.Balance = 10;

       // do some other process
       // Before the subscriber object being destroyed 
       // unsubscribe to an event
       bankAccount.BalanceChanged -= 
            BankAccount_BalanceChanged;
        Console.ReadLine();
     }
   static void BankAccount_BalanceChanged(object sender,
              BalanceChangedEventArgs args)
     {
       Console.WriteLine("Balance= {0}", args.NewBalance);
     }
}
  • In the above console application example has subscribed to BankAccount object BalanceChanged event using overloaded '+' operator. While subscribing to the event, you need to mention what the event handler method.Here the Console application is called the subscriber for the event.

    In Visual Studio "thunder icon" is used to represent the event as shown in the above event subscription screenshot.

  • After the event subscription, the subscribers will be notified whenever an event occurs. In our current C# example, we are assigning a new value to Balance property on the BankAccount object, which results in an event being raised. Hence the subscribed event handler "BankAccount_BalanceChanged" method will be invoked.
  • Interesting thing is event arguments. In our example the event argument passed is BalanceChangedEventArgs. It will indicate two things, new balance amount (new state) and previous balance (old state). The BankAccount_BalanceChanged event handling method is making use of the event argument to print the new balance.

Unsubscribing to events in C#

Once you subscribed to an event, you should always unsubscribe to the event. Event unsubscribing is like telling the event raiser that you are no longer interested in the event. During event un-subscription, your event handling method will be removed from the notification list what your event raiser maintains. Make it a practice to always unsubscribing to an event otherwise it may lead to memory leaks in your application.

Event subscription will be done using overloaded '-' minus operator like below:

// Event will be unsubscribed using overloaded
// minus (-) operator.
bankAccount.BalanceChanged -= BankAccount_BalanceChanged;

Download sample tutorial project

You can download the C# events tutorial project from the google drive share.

26 December 2014

a practical example for C# Extension methods

Recently while working on implementation of a new functionality, I noticed some of our junior C# developers not used Extension methods where Extension methods meant to be used to reduce duplicate code(DRY principle) and to make the code a bit more readable.

If you don't know what are the extension method refer my another article Extension methods.

Let's discuss on what was the state of code without extension methods and after using extension methods.

Business entities used in the application

class Furniture
{
 public string Name { get; set; }
 public string Id { get; set; }
 public FurnitureOwnershipType OwnershipType { get; set; }
}

enum FurnitureOwnershipType
 {
   Rented,
   Own
 }

Code before using extension methods

IList<Furniture> furnitures = new List<Furniture>();

furnitures.Add(new Furniture() { 
              Id = "1", Name = "Chair"
              OwnershipType = FurnitureOwnershipType.Own });

furnitures.Add(new Furniture() { 
              Id = "1", Name = "Sofa"
              OwnershipType =FurnitureOwnershipType.Rented });

furnitures.Add(new Furniture() { 
              Id = "3", Name = "Freezer"
              OwnershipType = FurnitureOwnershipType.Rented });
// The below code was duplicated in many controllers
// to filter furnitures for a given OwnershipType
IEnumerable<Furniture> rentedFurnitures = 
furnitures.Where(f => f.OwnershipType == 
                      FurnitureOwnershipType.Rented);

Code after using extension methods

static class Extensions
{
  public static IEnumerable<Furniture> 
  GetForOwnershipType(this IEnumerable<Furniture> furnitures,  
  FurnitureOwnershipType ownershipType)
   {
     return furnitures.Where(
        f => f.OwnershipType == ownershipType);
   }
}

// Using extension method GetForOwnershipType()
// defined on IEnumerable<Furniture>
furnitures.GetForOwnershipType(FurnitureOwnershipType.Rented);

Created the extension method GetForOwnershipType() for IEnumerable<Furniture> type as seen in the above code. Later the code become easy to read and duplicated code is eliminated.

07 December 2014

Why to use delegates

Often this one of the questions you will be asked in C# .NET interview question. Then the usual answer is "Delegates are pointers to functions/methods" and "they are used to create events". There is nothing wrong with the answer but that is just a delegate definition. Now let's find the real convincing answer to the question, "Why delegates?"

Let's get started by creating a delegate in C# .NET Console application to understand Why Delegates.

public class Employee
{
 public delegate string EmployeeDisplayFormatter(Employee employee);

 public EmployeeDisplayFormatter DisplayFormatter;
 public string Name;
 public string Department;

 public override string ToString()
 {
  if (DisplayFormatter != null)
   {
     return DisplayFormatter(this);
   }
  return base.ToString();
  }
}

In the above Employee class, there is a delegate by name EmployeeDisplayFormatter. By definition, EmployeeDisplayFormatter delegate can point to any method which takes in Employee object as a parameter and returns a string value. If you look into Employee class ToString() method, it is invoking the delegate to get return value.

Advantage of using delegates

With delegates implementation, in future if you want to customize return value from the Employee's ToString() method you just need to pass different method implementation for same delegate.

  • Have a look at the console application example at the end of the post. Employee object's DisplayFormatter delegate is pointing to GetEmployeeDisplayNameWithDept1() method. So whenever Employee class ToString() method is used, you will get the return value depending on what is defined in the GetEmployeeDisplayNameWithDept1() method.

    static string GetEmployeeDisplayNameWithDept1
         (Employee employee)
    {
     return employee.Name + " works for " + employee.Department;
    }

    Employee employee = new Employee() { 
          Name = "Ranganath", Department = "IT" };
    employee.DisplayFormatter = GetEmployeeDisplayNameWithDept1;
    string displayText = employee.ToString();
    Console.WriteLine(displayText);

    Ranganath works for IT

  • Say for some other requirement you want change what what ToString() method returns. Using the delegate approach it has been made lot easier. Now you just need to Create a another method for your need matching the definition of the DisplayFormatter delegate.

    static string GetEmployeeDisplayNameWithDept2
       (Employee employee)
    {
       return employee.Name +" ("+ employee.Department+")";
    }

    Employee employee = new Employee() 
    { Name = "Ranganath", Department = "IT" };
    employee.DisplayFormatter = GetEmployeeDisplayNameWithDept2;
    string displayText = employee.ToString();
    Console.WriteLine(displayText);

    Ranganath(IT)

  • Without using the delegates here you had left with no option to modify Employee class to change what ToString() method returns each time your requirements changes. This formatting requirements are need is going change from time to time and from screen to screen in applications. So keeping this formatting logic outside the class by using delegates gives us the flexible design.

C# .NET program example showing why delegates

class Program
{
  static void Main(string[] args)
    {
       Employee employee = new Employee() 
           { Name = "Ranganath", Department = "IT" };

   employee.DisplayFormatter = GetEmployeeDisplayNameWithDept1;
   string displayText = employee.ToString();
   Console.WriteLine(displayText);
   Console.Read();
     }

   static string GetEmployeeDisplayNameWithDept1(Employee employee)
     {
       return employee.Name + " works for " +
       employee.Department;
     }

   static string GetEmployeeDisplayNameWithDept2(Employee employee)
     {
       return employee.Name +" ("+ employee.Department+")";
     }
 }

Hope now you understood when and why to use delegates. Please feel free to mention your comments!.

Also recently I posted another article to related delegates called Generic Delegates

07 June 2014

difference between compile time and run-time polymorphism

In this tutorial post let's understand what is polymorphism and what are the difference between compile time polymorphism and runtime polymorphism.

What is polymorphism

Polymorphism means exhibition in many forms. "Poly" means multiple and "morph" means forms. Combining the two words it becomes the exhibition of multiple forms.

polymorphism is having two types. One is called compile-time polymorphism and other is run time polymorphism.

First let's understand compile time polymorphism

class  Program
{
  static void Main(string[] args)
  {
   // passing 2 values to Add() method 
   // calls 2 parameters method
   long sum = Calculator.Add(1, 2);
   Console.WriteLine(sum);
   // Passing 3 values to Add() method 
   // calls 3 parameters method
   sum = Calculator.Add(1, 2, 3);
   Console.WriteLine(sum);
   Console.Read();
   }
}
public static class Calculator
{
public static long Add(int par1, int par2)
 {
   Console.WriteLine("Two parameter method called");
   long sum = par1+ par2;
   return sum;
 }
 public static long Add(int par1, int par2, int par3)
 {
  Console.WriteLine("Three parameter method called");
  long sum = par1 + par2 + par3;
  return sum;
  }
}

Output of the above function overloading program:

Two parameter Add() method called
3
Three parameter Add() method called
6

In the above Calculator class, we have two methods with the same name Add(). One of the methods is taking in two parameters; whereas the other method is taking in 3 parameters. Depending on how many parameters we are passing to a method, a different method is called. Here the name of the method is same, only the number of parameters is varying. This is called function overloading. So using function overloading we can achieve compile-time polymorphism.

Why its called compile time polymorphism?

Which methods get executed will be determined at the time of compilation only. Hence this is called compile time polymorphism. Because the method invocation is decided at compile time only, it cannot change at runtime based on the context. Hence compile-time polymorphism is also called static polymorphism.

Using Function overloading we can implement compile-time polymorphism.

Now let's understand the run time polymorphism

The best is to go through a code example.

class Program
{
 static void Main(string[] args)
 {
  //doctor variable refers to 
  //instance of base Doctor class
  Doctor doctor = new Doctor();
  doctor.TreatPatient();
  // doctor variable refers to 
  // instance of derived Surgeon class.
  doctor = new Surgeon();
  doctor.TreatPatient();
  Console.Read();
  }
}

public class Doctor
{
public virtual void TreatPatient()
 {
Console.WriteLine("Doctor class: I diagnose 
      patients and prescribe medicine."
);
 }
}

public class Surgeon : Doctor
{
 // Override the behavior of the base 
 // class and customize it.
 public override void TreatPatient()
 {
 Console.WriteLine("Surgeon class:
                   I do surgery."
);
 base.TreatPatient();
 }
}

Output of the above function overriding program:

Doctor class: I diagnose patients and prescribe medicine.
Surgeon class: I do surgery.
Doctor class: I diagnose patients and prescribe medicine.

In above program, Doctor is the base class and Surgeon is derived class. In Doctor class, the method TreatPatient() is defined as virtual. That means, the derived classes can override the behavior of the base class. In our example the derived class, Surgeon is specialized form of Doctor, who can do surgery and hence the TreatPatient() method is overridden.

For Doctor type variable, when the Doctor class instance [new Doctor()] is assigned and on invoking the TreatPatient() method, the Doctor class TreatPatinent() method gets executed.

Doctor class: I diagnose patients and prescribe medicine.

In the next line for the same doctor variable, instance of the derived class Surgeon [using new Surgeon()] is assigned and on invoking the TreatPatient() method, the Surgeon class TreatPatinet() method will get executed and displays the below output:

Surgeon class: I do surgery.
Doctor class: I diagnose patients and prescribe medicine.

Here depending on which type of the instance the doctor variable referring to, that respective type method gets invoked. So here the variable is same and method name called is same, but different implementation of the method will get executed. Its exhibiting different behavior depending on which instance of the class it refers to. So it's a polymorphism happening at runtime.

But why its called run-time polymorphism?

Which implementation of the TreatPatient() method should get executed is dynamic and decided at runtime depending on the instance the base class type variable is holding the reference to. And hence the name runtime polymorphism.

Using Function overriding we can implement run time polymorphism type.

Download Polymorphism demo project(project built on 3.5 .NET using VS 2008)

01 June 2014

difference between abstract class and interface in c#

When you start designing class level diagrams, knowing the difference between abstract class and interface helps you in choosing right designs.

Syntactical difference

  • Abstract class can have abstract and non abstract methods. Abstract methods cannot have implementation and non abstract methods will have implementation. And these non abstract can have reusable implementation for the derived class where applicable.
  • Interface methods cannot have implementation, they are just declaration.

Difference when it come to Inheritance

  • A C# class cannot inherit from more than one class.
  • However a C# class can inherit from more than one interface. In C# .NET multiple inheritance if needed can be achieved using interfaces. If two base interfaces have the same method we can use explicit interface implementation.

Which is more flexible? interface or abstract class?

Abstract class are flexible compare to an interface. Let's take an example.

Assume that you are building a library which has contract defined using interfaces. These libraries are used by a lot of projects in your organization. First, you have released contracts.dll. So people are using the contracts which are defined by interfaces.

Now new requirements have come, to meet those requirements you are required add a new method to the existing interface which is already in use by many projects. Later when you deploy this new contracts.dll containing the interface, all the existing implementation will start failing. This is because the classes which implemented the interfaces don't have the new method implementation. So interfaces aren't backward compatible.

Assume that for instance, you have defined your contracts using the abstract class instead of an interface. You can easily add new non abstract methods to your abstract class without breaking the existing implementations. Here the existing implementations are classes deriving from the abstract class. The newly added non abstract methods can throw System.NotImplementedException when released. Hence abstract classes are more flexible compared to interfaces.

RELATED ARTICLES

11 May 2014

why one shouldn't ignore code compile warnings

Recently I was working on a code re factoring; A method in class had duplicated code and wasn't following the DRY principle.

The method under question was building 3 similar objects but of different types. The code looked like below in simple:

public class Car 
{
public string Type{get;set;}
}

public List<Car> BuildCars()
{
  List<Car> cars = new List<Car>();

  // Build car of type 1
   Car type1Car = new Car(){Type=1};
   cars.Add(type1Car);

  // Build car of type 2
   Car type2Car = new Car(){Type=2};
   cars.Add(type2Car );

  // Build car of type 3
   Car type3Car = new Car(){Type=3};
   cars.Add(type3Car);

   return cars;
}

As one can see a lot of code is duplicated in the method BuildCars(). Duplicate code will suffer from below syndromes:

  • Duplicated code will not have good readability as the methods looks lengthy.
  • And also the code isn't maintainable as it is difficult to debug and apply defect fixes.

Hence I started with re factoring of the method. Created a new method BuildCar() like below:

public Car BuildCar(string type)
{
  Car car = new Car() {Type=1};
  return car;
}

Later as part of the refactoring added a new BuildCar() method and used it in the BuildCars(). Hence code become little more readable and more maintainable because of reduction in duplicate code.

public List<Car> BuildCars()
{
   List<Car> cars = new List<Car>();

   Car car= BuildCar(1);
   cars.Add(car);

   car= BuildCar(2);
   cars.Add(car);

   Car car= BuildCar(3);
   cars.Add(car);

   return cars;
}

Started debugging the code and found that cars returned from BuildCars() method are all of type 1!. Something went wrong with refactoring then. It didn't take much time to find the issue and correct it. Although it wasted some time!.

Corrected the BuildCar() method to use the input parameter type and everything started working as expected. The input variable 'type' was never used and 'type' was hardcoded to 1.

public Car BuildCar(string type)
{
  Car car = new Car() {Type=type};
  return car;
}

Then how one can prevent these kinds mistake from happening again?

Visual Studio will give a warning if a variable isn't used by default. So if I had used the Build Warnings window to see the "unused variable" warning then the mistake would have been prevented and there wouldn't have been a defect in my code.

So moral of the story is ALWAYS ENSURE ZERO WARNINGS! in your code.

20 April 2014

var keyword in C# exaplined: when to use it and when not

We tend to use the var keyword often to declare the class variables while writing C# code. This may be to avoid importing the namespaces or to save time writing the full name of the class variables. But it's very important to understand why the var keyword introduced?

var keyword meant to use only when the type of the variable is not known to you (i.e. Developer) and only known to the compiler. Use the var keyword when you are working with anonymous types. Let's consider an example.

var customers= from cust in customers
               where cust.City== "Bangalore" 
               select new { cust.Name, cust.Phone }; 
               //anonymous type

And var shouldn’t be used when you know the variable type already. Declare the variable with explicit type name like in the below example.

public class Customer
{
 string Name{get;set;}
 string City{get;set;}
 string Phone{get;set;}
}

var customers= from customer in customers 
                where customer.Name ="Ranganatha"
                select customer;

In the above C# LINQ query example we already know that, we are selecting Customer type, which is not an anonymous type. So usage of var keyword to declare the list of customer is not encouraged while writing code. So in the above example using explicit type declaration makes more sense.

// Use explicit type declaration when 
// type is already known
List<Customer> customers= from customer in customers 
                where customer.Name ="Ranganatha"
                select customer;

When code is more explicit in nature, it becomes more readable. Remember code is written once, however debugged and read more times. So readability of the code important.

25 January 2014

extension methods in c#

Extension methods adds a method to class without modifying the class definition, so it's useful in adding method to a third party class within a namespace scope.

Uday is c# developer, he is using third party library in his project. A class in third party library, doesn't have a method, what Uday needs for his requirement. He cannot modify the third party library class to add the method what he needs. Using extension methods one can add method to class without modifying the class itself; Let's see how!

Go through the below tutorial topics to understand extension methods in c# in detail.

  1. Code sample in C# without using extension methods
  2. C# code example with extension methods
  3. How extension method works?
  4. extension methods in LINQ

Code sample in C# without using extension methods

// Class defined in Contracts.dll assembly.
// Class defined in Contracts.dll assembly.
public class Customer
{
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public DateTime DOB {get;set;}

public string GetDisplayInfo()
  {
   return this.FirstName+ " "+this.LastName+ 
                   "born on" + this.DOB.ToString();
  }
}

The above Customer class has GetDisplayInfo method, but developer using the class also needs a method just to display customer full name. Such method doesn't exist on the Customer class and cannot edit the Customer class itself to include the method required. The reasons could be:

  • Such class is a.NET library class.
  • The class is in some third party library.
  • The new method in need is very specific to a requirement and may not be useful to rest of the consumers of the Customer class.

Then developer will mostly relent to static method in a static helper class like below:

// Helper class defined in application assembly
public static class CustomerHelper
{
   public string GetFullName(Customer customer)
    {
     return customer.FirstName + customer.LastName;
    }
}

Usage of such static helper class would look like below:

Customer customer = new Customer();
string fullName = CustomerHelper.GetFullName(customer);

With static class helpers, we can get the required functionality. But we have to pass in the customer object to get the customer full name. Wouldn't it be nice? if we have a mechanism to get the full name by calling a method on the customer object itself so that all the calling code will become simple and also easy to read. But how can it be done? Answer is simple, use extension methods.

C# code example with extension methods

Let's rewrite the GetFullName method using extension methods in C#.

namespace CustomerUtility {
 public static class CustomerHelper  {
   public string GetFullName(this Customer customer) {
        return customer.FirstName + customer.LastName;
    }
  }
}
Here GetFullName is a extension method to Customer class and let's see understand, how extension method will be defined:
  1. Extension methods should always be created inside a static class. Here CustomerUtility is such static class.
  2. Extension method is a static method with special this parameter specifying the class to which we need the extension method. Here Customer is such class.
  3. Extension methods will be available only within the containing static class's namespace scope. Here CustomerUtility is such namespace. So to use any extension method you need to import respective namespace first.

Now, let's see how code will be simple and easy to read using extension method:

using CustomerUtility;
// Inside a method you need customer full name.
{
Customer customer = new Customer();
string fullName = customer.GetFullName();
}

Visual Studio showing the Extension methods

Visual Studio shows the extension methods with (extension) prefixed.

Extension methods display in Visual Studio IDE

How extension method works?

Extension method invocations gets bound to respective static methods during compilation. Open the assembly in ILDASM to view the IL(Intermediate Language); You will find that the IL code of the lines which invokes the extension method is same as that of direct static method invocation.

Recently I have posted another article explaining a practical example of Extension methods.

19 January 2014

nullable types in C#

Nullable types in C# .NET allows assigning null values to structures. By declaring a structure as nullable type, null value can be assigned to structure variable.

In this tutorial, let's understand more about nullable types, by going through the below sections:

  1. Why nullable types?
  2. How to declare nullable types?
  3. Working with APIs of nullable types with examples
  4. How .NET has defined nullable types?

Why nullable types?

Let's consider an example of developing a Customer management application; The application stores the Customers details including Date of Birth and Annual Salary. As per business requirement, a record can exist with no values for the Date of Birth and Annual Salary fields. So when it comes to DB design, the columns to store these two fields will be nullable.

While designing app layer contracts, you will start thinking about business entities in the system. The Customer entity class has Date of Birth and Annual Salary properties. So you declare Date of Birth as DateTime & Annual Salary as Integer type. Both DateTime and Integer are Structures and they cannot have null values. But application needs these two fields to have null when a customer hasn't specified values. But null value is not supported for structure data types.

public class Customer 
{
 public DateTime DateOfBirth {get;set;}
 public int AnnualSalary {get;set;}
}

So there is a problem. This problem can be workaround by assigning zero to Salary and the corresponding interpretation in UI layer to display Not Specified when value is zero.

The workaround for DateTime field is not easy. The default value for DateTime structure in .NET is less than the allowed value in MS SQL server database DateTime column. So you need to do more workaround which isn't straightforward and your fellow developers will have a difficult time in understanding such code and hence code will become less maintainable. So these workarounds are not clean design.

These problems can be solved by making .NET structure fields to have a null value. This can be achieved using nullable structure types. Then, let's see how?

How to declare nullable types?

Nullable types declared with "question mark - ?" suffixed to the structure data type like below:

public DateTime? DateOfBirth {get;set;}
public int? AnnualSalary {get;set;}

Working with APIs of nullable types with examples

Nullable types notably has two properties HasValue and Value and GetValueOrDefault method with two overloads.

  • HasValue: HasValue boolean property indicates whether nullable type has any value other than null.
    DateTime? DateOfBirth {get;set;}
    if(DateOfBirth.HasValue) {
     // Nullable type has valid value.
    }
  • Value: Value is a property of underlining structure type. Value is read-only property, you cannot assign any value directly to this.
    DateTime? DateOfBirth {get;set;}

    if(DateOfBirth.HasValue) 
    {
      DateTime value = DateOfBirth.Value;
    }
  • GetValueOrDefault: This method on the Nullable type returns the underlining structure value if has value else returns the default value of the underlining structure type.
    int? annualSalary;

    // This returns zero; because 
    // integer value type default value is zero
    int salary = annualSalary.GetValueOrDefault();

    // Overloaded method taking default value 
    // to return if nullable type value is null.
    salary = annualSalary.GetValueOrDefault(1213)

How .NET has defined nullable types

In mscorlib.dll assembly Nullable types are declared as structure with Generics where T can only be a value type.

public struct Nullable where T : struct
 {

 }

Reference types like classes cannot be declared as nullable. If you do so, you will get the below error:

The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable' GetValueOrDefault

14 January 2014

optional parameters in c#

C# optional parameters make method parameters optional; such parameters aren't required to pass while calling a method. Specified default value will be used when parameters not passed.

In this article let's understand C# optional parameters in detail by going through the below tutorial sections:

  1. What is the need for optional parameters?
  2. How to declare and use methods with optional parameters?
  3. Compiler role in getting optional parameters working
  4. Caveats you should be aware while working with optional parameter

What is the need for optional parameters?

Let's consider a C# code sample.

public class Customer
{
   public string Name {get;set;}
   public string MobileNumber{get;set;}
   public CustomerAddress Address {get;set;}
   public Customer(string name, sting mobileNumber)
    {
       this.Name = name;  
       this.MobileNumber = mobileNumber;  
    }
   public Customer(string name, string mobileNumber, 
                   CustomerAddress address)
    {
       this.Name = name;  
       this.MobileNumber = mobileNumber;
       this.Address = address;
    }
}
  • In the above Customer C# class example, there are two constructors, one is taking two parameters and other is taking three parameters.These are overloaded constructors, to provide the flexibility of creating Customer object without the need of CustomerAddress object being passed in.
  • Second constructor exist just for accepting the parameter CustomerAddress object, which is optional at the time of creating the instance of the Customer class.
  • Creating a second constructor just for accepting an optional parameter is maintenance overhead.

Using optional parameters, the second Customer class constructor can be avoided. So there will be less code in the class to achieve the same using optional parameter. But let's see how!

How to declare and use methods with optional parameters?

Using optional parameters in constructor methods, the Customer class code can re-written as below:

public class Customer
{
   public string Name {get;set;}
   public string MobileNumber{get;set;}
   public CustomerAddress Address {get;set;}
   
   public Customer(string name, string mobileNumber, 
                   CustomerAddress address = null)
    {
       this.Name = name;  
       this.MobileNumber = mobileNumber;
       this.Address = address;
    }
}
  • CustomerAddress is declared as optional parameter with the default value null.
    CustomerAddress address = null;
    The default value assigned to optional parameters using = sign in the method declaration.
  • Lines of code is reduced with optional parameter by removing the overloaded constructor and the Customer class code now looks less verbose!
  • Let's see how can we invoke methods declared with optional parameters.
  • //Not specifying optional parameter value
    Customer cust=new Customer("Arun""12345");

    //passing the optional parameter value
    cust=new Customer("Arun""12345",
                           new CustomerAddress());
    1. The first constructor method not passing value for the CustomerAddress explicitly which is a optional parameter. When no value passed for this optional parameter, the defined default value null is used.
    2. The second constructor method is passing value for the CustomerAddress. So the passed in value will be used.
  • Visual Studio intellisense showing the optional parameters:

    optional parameters in C# shown in Visual Studio

Compiler role in getting optional parameters working

After knowing how to use optional parameter, it's good to know how optional parameters works behind the scene.

  1. Let's consider the same Customer class constructor methods declared with optional parameters. When creating instance don't pass the value for optional parameter. When the code which is invoking the constructor is invoked, the C# compiler puts in the default value automatically for optional parameters which aren't passed.
  2. When you open the class in ILSPY assembly decompiler you can see that, parameter default value is explicitly put in by C# compiler. So at compile time only, the default value for the optional parameters will be binded.
  3. optional parameters in C# shown in ILSPY

Caveats you should be aware while working with optional parameter

As at compilation time, the optional parameters values will be explicitly binded just like named parameters you should be aware a situation.

Let's consider that you define the Customer class and related classes in one assembly and you are referring that assembly in another solution and creating Customer instance.

  1. First Scenario:Both the assemblies are compiled and deployed. Later modify the Customer class constructor assigning different default value instead of earlier null. Compile only that assembly and deploy.
    public Customer(string name, string mobileNumber, 
          CustomerAddress address = new CustomerAddress())
        {
           this.Name = name;  
           this.MobileNumber = mobileNumber;
           this.Address = address;
        }
    }
    Though the default value for optional parameter is changed, when other assembly code is executed, it will still pass the old optional parameter value which is null. Because that assembly is not yet compiled using latest assembly containing Customer class. Tricky interview question isn't?
  2. Second scenario:This time let's change the number of optional parameters with Customer class constructor by adding a new optional parameters, compile only that assembly & deploy it. This time the code will break throwing System.MissingMethodException runtime exception while trying to create an instance of the Customer class.

    This happens because the assembly which is referring Customer assembly, is not yet compiled and it's trying to create Customer instance by invoking 3 parameter constructor; Which doesn't exist in the latest Customer assembly and hence System.MissingMethodException is thrown. Another tricky interview question isn't?

01 January 2014

partial class in c#

Ramesh is UX specialist & Yadav is a C# developer; Both are working for a project and building a screen in windows form application and needs the same class file; Ramesh wants to create user interface & Yadav want to add code behind logic. So you can see, there is a competition between these two guys for the same C# class file. Often it happens, they are overwriting each other changes and spending time in merging the changes.

This is definitely a problem and needs to be addressed. Using the partial class, the competition for the same c# class file problem can be solved. So let's go through the below sections to understand partial class in c#.

  1. What are partial classes?
  2. When to use partial class?
  3. How to create partial class in C#
  4. Real world example of partial class
  5. More about partial class

What are partial classes?

Partial class can be defined in more than one place; they can be defined in more than one file. A portion of the class can be written in a file and another part of the class can be coded in another different file.

When to use partial class?

If there is a class file which could be updated by different kind of authors, you should consider to use partial class. The authors can be C# developer, User Interface (UI) designer & tools like Visual Studio Win forms Designer.

For example, if you design windows form using the drag & drop feature of Visual Studio, then it's better to allow a different file for Visual Studio; as it will help separation of concerns. The developer is concerned about adding code-behind logic, whereas designer is concerned about a form's look and feel. Allowing these authors to work on different class files helps to avoid merge issues and get rid of file overwrite problems.

How to create partial class in C#

Partial classes will be created using the partial keyword.

public partial class Customer
{
  public string _name;
   
  public Customer(string name)
  {
    _name = name;
  }
}

Let's define other partial class.

public partial class Customer
{
   public void DisplayCustomerInfo()
   {
    Console.WriteLine("Customer name: "+ _name);
   }
}
  • As you can see the partial class Customer is defined in two different code snippets. These partial class definitions can exist different files.
  • The method DisplayCustomerInfo() can access the private member, _name defined in other partial class. It works because the class is same, but just that, they exist in two different files.

Real world example of partial class

Partial classes are mainly used by CODE Generators. On such example is with ASMX web service proxy generation in Visual Studio. Recently I blogged about the advantage of web service proxy classes being generated as Partial classes.

partial class practical use case with web service proxy regeneration

29 December 2013

c# class tutorial

Classes are ubiquitous in Object-Oriented Programming & Systems. Classes are very important in C# programming as well; we cannot assume a single program in OOPS without class. Then let's go through the tutorial, class in C#.

  1. What are classes?
  2. Defining a class in C#
  3. What constitutes a class with C# class example
  4. Types of classes in C#

What are classes?

Let's take an example of a real-world entity. You ask your friend, which movie they last saw? One friend might say, "I saw Hindi movie Dhoom3 - Aamir Khan acting suburb, Krishna Acharya has directed, one & half hour long and U/A certificate etc".

So the movie entity has Name, Actors, Director, Duration and U/A, etc attribute and these attributes define a movie. If you ask another friend, more or less he will also give the details of the movies in the form of same attributes. So A set of attributes are defining a movie and these set of attributes vary from movie to movie.

If movie entity has to be represented in OOPS, we could create Movie Class with all the common attributes defined as properties; and create different movies like Dhoom3, Titanic, Avatar, etc. So, varying values for set of attributes are defining different movies.

So, classes are the nothing but a template or blueprint used to create objects/instances of a certain entity. We can also say a class represents, an entity and defines how their the different instances looks and behaves.

Defining a class in C#

public class Movie
{
   
}
  • In C# .NET, a class will be defined using the class keyword.
  • Every class will have name;in the above C# code sample, class name is Movie.
  • The class will have its entire definition defined within the { flower brackets }.

What constitutes a class with C# class example

In short class will have a name, attributes defined as properties, behaviors /capabilities defined as methods and constructors to create instances of the class.

Let's go through an example of class, SmtpClient to understand what constitutes a class. SmtpClient class is under System.net.Mail namespace which is present in .NET framework. In an high level the SmtpClient class looks like below:

namespace System.Net.Mail
{
   public class SmtpClient
    {
     // Properties which defines class.
      public string Host { get; set; }
      public int Port { get; set; }

      // Constructor to create class instance
      public SmtpClient(string host, int port)
      { 
        // Constructor logic the goes here...
      }
 
      public void Send(string from,string recipients,
                       string subject,string body) 
      {
       // method logic goes here...
      }
       
    }
}
  • Class name: In the above c# code sample, SmptClient is the class name. Class name used to uniquely identify a class.
    public class SmtpClient
  • Namespace: Namespace used to group related classes together. Class names should be unique in a given namespace. In the above C# class example, System.Net.Mail is the namespace.
  • namespace System.Net.Mail
  • Properties: Properties helps to build a instance of the class. If you have two different set of values for a given entity, two different instances/objects will be created; i.e class instances vary by their properties values.
    public string Host { get; set; }
    public int Port { get; set; }

    The above C# class code sample, has two properties Host & Port.

    Consider another example of Person class. Two different persons will have different name, profession, address, etc. So name, profession and address, etc represent a Person. Hence Person class developer defines class with Name, Profession and Address as properties.

  • Constructors: Constructors are special methods in a class used to create an instance of the class.
    public SmtpClient(string host, int post)
      { 
            // Constructor logic the goes here...
      }

    Constructors should take all the required/mandatory parameters as arguments; So that, after you have the objects created using constructors, the object should be usable and shouldn't throw exceptions when a method is invoked using the object.

  • Methods: The capabilities of a class will be exposed as methods. For example, in the above SmtpClient class, Send() method sends the email out.
    public void Send(string from,string recipients,
                     string subject,string body) 
      {
           // method logic goes here...
      }

    The Send() method takes parameters which tells, what an email should be sent and for whom an email should be sent. i.e method arguments defines how the capabilities of the class will be used to get the desired result.

  • Class access specifier: Last but not the least, SmtpClient is defined with public access specifier. Meaning its visible to all.
    public class SmtpClient

    We can specify different access specifiers for the class i.e. public, internal, private, etc

Types of classes in C#

In C# we can define classes as static, abstract, sealed and partial. Let's go through one by one:

  • Abstract class: Abstract classes cannot be instantiated. These are mainly created to act as base class.
  • Static class: Static classes cannot be instantiated and no one can inherit from static classes. Mainly used to act as helper classes.
  • Sealed class: Sealed classes cannot be inherited. In case if you don't want to make class to be inherited, consider marking a class as sealed .
  • Partial class: Partial classes is not really a different type of class. Partial classes allows some part of the class definition coded in file and another part of the class coded in different file.

    For example, partial classes are used by Visual Studio Windows form designer, where in which form designer partial class will be generated by Visual Studio and code behind partial class is created by developer.

25 December 2013

c# methods explained in detail

When programming you use classes, methods, properties and data members, etc. In this tutorial let's discuss methods in C# language.

  1. What is a method?
  2. What constitute a method?
  3. A typical method in C# language
  4. Types of methods

What is a method?

A method usually performs something when it is invoked. What a method performs, depends on what logic you put in the method body.

For example, consider a Car class; We can define Drive() method to drive the car forward and Reverse() method to go reverse. Here both Drive() and Reverse() methods perform some actions, they modify the state of the object. i.e., Car position.

Consider a Television set's remote control example; It controls the behaviour of the television. You can implement VolumeUp(), VoulmeDown(), ChangeChannel() and ScanChannels(), etc, methods to control the behaviour of the TV.

What constitutes a method?

  1. Method name:

    Used to identify a method and invoke the method.

  2. Method arguments or parameters:

    A method can have multiple or no parameters. Method arguments can be of different types based on your requirements.

  3. Method body:

    Method body defines the behaviour. It is the crux of the method.

  4. Method return type:

    A method can return a single entity or its return type can be void, returning nothing

  5. Method access specifier:

    Used to define the visibility of the method. Using method access specifier developer defines, who can invoke the method and who cannot invoke it. It can be any of the C# access specifier i.e., private, internal, protected, internal or protected internal.

  6. Method name, argument list, return type and access specifier together forms the method signature.

A typical method in C# language

As always going through an example is better idea to understand something new. Let's consider the below C# class, Calculator.
public class Calculator
{
    public long Add(int a, int b)
     {
       // method logic...
       int sum = a+b;
      
      // Method is returning
       return sum;
     }
}
In the above C# code example, Calculator is a class and has a method Add().
  1. Add is a method name.
  2. (int a, int b) is an arguments list. Where a & b is parameters of integer type.
  3. What you can see within the { flower brackets } is method body.
  4. At the end of the method body, there is a return statement, returning sum. Method execution stops when the control flow in a method encounters a return statement.
  5. The Add() method has public access specifier, meaning anybody who can use the class can invoke the method. i.e. It's visible to all.

Types of methods

There are different method types. Let's go one by one briefly:
  1. Instance methods
  2. Static methods
  3. Constructors & Destructors methods
  4. Abstract & concrete methods
  5. Virtual & overridden methods
  6. Overloaded methods
  7. Partial methods
  8. Extension methods

Instance methods

Method which can only be invoked using class instance are called instance method. i.e., in the above Calculator class, the Add() method can be invoked using the instance.

Calculator calculator = new Calculator();
long sum = calculator.Add(100, 200);

Static methods

Methods can be declared static, meaning using class itself such method can be invoked. Using class instance such methods cannot be invoked.

Always declare a method as a static method, if doesn't use any instance members. Static methods perform little better compared to instance methods.

Let's add a static method to the Calculator class and see how it can be invoked.

public class Calculator
{
    public static void DisplayManufacturer()
     {
      Console.Writeline("Casio");
     }
}
  // static method invoked using the Calculator class.
  Calculator.DisplayManufacturer();

Constructors & Destructors methods

Constructor and Destructors are also method in the class, but they are special methods. Constructors are used to create an instance of a class and Destructors used to destroy the objects.

Constructors can have one, multiple or no parameters. The Constructor without any parameter is referred as default constructor. Even if the developer doesn't define a parameterless constructor they exist by default. Constructors don't have a return type; their return type is implicit. i.e. It can only return the same class object.

public class Calculator
{
   public string Model{get;set;}
   public Calculator(string model)
     {
        this.Model = model;
     }
}

// Instance created using the parameterless constructor.
Calculator calculator= new Calculator();

// Instance created using the parameter constructor.
Calculator calculator= new Calculator("2012-FC");

Destructors are also called finalizers. Destructors cannot have any parameters. In C# .NET they cannot be invoked by developers, they get invoked by the framework during the Garbage collection process.

Let's consider an example of Destructors with the same Calculator class:

public class Calculator
{
   // Finalizer method
   ~Calculator()
     {
       
     }
}

Abstract & concrete methods

Abstract methods are declared as abstract and just have method declaration. The abstract methods will not have method definition or method body. A class containing a abstract method should be declared a abstract class. In the C# code sample, the Car class has the Drive() method which is an abstract method.

public abstract class Car
{
   public abstract Drive();
}

The method which has the definition or provide implementation are called concrete methods. In this post, the Caluculator class's Add() method is an example of concrete method.

Virtual & overridden methods

Methods can be declared as virtual; meaning such method can be overridden in the derived class. When writing a class if you think derived class can customize the behavior then mark the method as virtual.

Methods declared virtual in derived class, can be overridden by the derived class to customize the behavior accordingly.

Refer article, Function overriding in C# .NET for more details on Virtual & overridden methods

Overloaded methods

Method can be overloaded in a class or struct to achieve compile time polymporphism. Methods with the same name and varying parameter list by number and data types of arguments are called overloaded methods.

Partial methods

Partial methods can be declared in one partial class and have implementation in another same name partial class. Partial methods are introduced for situations where you are generating code automatically using tools.

Refer another detailed tutorial on partial methods in C# .NET to know in detail.

Extension methods

Extension methods adds a method to class without modifying the class definition, so it's useful in adding method to a third party class within a namespace scope. To understand more go through tutorial on C# extension methods.