Friday, March 30, 2012

Using ADO.NET - Part I

In next few posts we will discuss ADO.NET object and how you can use it to connect to SQL Server database (you can connect to other databases as well, but here we will limit our discussion to SQL Server) and then work with the data. This will be a nice segway into other ways of working with data such as Entity Framework, Linq etc.

In this post we will discuss the following topics

  • Connecting to a database
  • Using SQL Command Object
  • Using Data Reader Object
ADO.NET Provides SQL Connection Object and SQL Command Object that work together to retrieve/select/update your data. 

Let's consider an example. Notice, you have to reference System.Data.SqlClient class to work with ADO.NET object.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ADONET2ConnectedCompact
{
    class Program
    {
        static void Main(string[] args)
        {
            // Step 1: Handshake with the database
            string connectionstring = System.Configuration.ConfigurationManager.
            ConnectionStrings["MyDBConnection"].ToString();
           SqlConnection myConnection = new SqlConnection(connectionstring);
           myConnection.Open();
           try
           {
               // Step 2: Specify a command (request)
               SqlCommand myCommand = myConnection.CreateCommand();

               myCommand.CommandType = CommandType.Text;
               myCommand.CommandText = "SELECT TOP 10 CustomerID,
               AccountNumber,CustomerType FROM Sales.Customer";
               SqlDataReader dr;

               dr = myCommand.ExecuteReader();


               // Step 3: Use the data

               while (dr.Read())
               {
                   Console.WriteLine(dr[0].ToString() + " " + dr[1] + 
                   " " + dr[2]);
               }
               Console.ReadLine();
           }
           catch (Exception ex)
           {
               Console.WriteLine("Exception{0}: ", ex.Message);
           }
           finally
           {
               myConnection.Close();
           }
            

        }
    }
}


In this example, we used inline SQL script as opposed to stored procedure. But, you can use stored procedure instead, just change the command type from CommandType.Text to CommandType.StoredProcedure. In this blog we will not be discussing SQL Server but if you would like to know more about SQL Server, checkout my SQL Blog.

We used connection string from the App.Config file to get the SQL Server, database and login information. Below is a snippet from App.Config that pertains to connection string.
<connectionStrings>
    <add name="MyDBConnection" connectionString="Data Source=HOME-PC\SQL2008;Integrated Security=true;Initial Catalog=AdventureWorks;"/>
  </connectionStrings>

Data Reader
There are couple of ways you can retrieve data from the SQL Server. Data Reader is one of them. The key characteristics of data reader are that it is connected, read only and forward only. You cannot use data reader while you are disconnected from the database or to update/insert data.

Notice the user of try / catch / finally. You want to make sure you always close your SQL connection.

There are other ways to read data namely data adapter. We will review data adapter in future post.

Thank you.


Sunday, March 25, 2012

Implementing IDisposable Interface Part - II

In previous post we discussed implementing IDisposable interface for unmanaged code. Even though your class may implement IDisposable interface and you release the resources, but what if a developer never calls the dispose method? Since GC can't free up resources claimed by your unmanaged code and if you forgot to call Dispose method, you are back to square one.

What if we somehow force Garbage Collector to call the Dispose method for our unmanaged code? This will be best of both worlds - you can free up resources as soon as you are done, but if you forgot to free up resources, you can be sure that GC at some point will reclaim those resources. In order to force GC to free up unmanaged resources, you have to implement your own version of Finalize method. GC will use this finalize method to destroy your objects. Declaring a finalize method in C# is similar to destructor method you create in C++

Lets extend the class we created in previous post.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace IDisposableInterface
{
    class Unmanaged:IDisposable
    
    {
        private bool _disposed;
        private IntPtr _handle;

        //initializer method 
        public Unmanaged()
    {
        //we create a new pointer and associate it with the current process
        // This is unmanaged code and _handle must be disposed explicity 
        //and GC will not collect it
         _handle = new IntPtr();
        _handle = System.Diagnostics.Process.GetCurrentProcess().Handle;
    }
        public IntPtr Handle
        {
            get { return _handle; }
        }
      //notice we have declared this method as private because this is not thread      -safe 
      //and should only be called once. Here we are declaring a global variable        //to ensure it only executes once.
       private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                //release unmanaged resources
                 _handle = IntPtr.Zero;
                _disposed = true;
            }
        }
        public void Dispose()
        {
            Dispose(true);
        }
       //Create Finalize Method. This will be called by GC to dispose off 
       //unmanaged resources.
       ~Unmanaged()
       {
          Dispose(true);
       }
    }
}

While this works, but you could be destroying an object twice and may result in an error. Even if it doesn't result in an error, you are still unnecessarily calling Dispose more than once. What if you can design it in a way that GC only calls your dispose method only when you haven't called it? You can do this by modifying your Dispose method and adding SuppressFinalize.

public void Dispose()
        {
            Dispose(true);
            //don't bother trying to dispose this object.
            GC.SuppressFinalize(this); 
        }

Now, if you have called the Dispose method yourself, you have directed GC to don't bother disposing this object. If you didn't call Dispose method, GC will take care of it.

In reality, most classes that have some unmanaged code almost always have the managed code as well. Wouldn't it be nice to dispose off your managed resources when you destroy your unmanaged resources as well? GC will eventually destroy your managed resources, but why wait when you know you don't need them anymore? Especially if they consume large amount of memory. Let's modify the above class and create a handle to read a file from the hard-drive.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace IDisposableInterface
{
    class Unmanaged:IDisposable
    
    {
        private bool _disposed;
        private IntPtr _handle;
        private System.IO.Stream _filestream;   //managed resource
        //initializer method 
        public Unmanaged()
    {
        //we create a new pointer and associate it with the current process
        // This is unmanaged code and _handle must be disposed explicity 
        //and GC will not collect it
         _handle = new IntPtr();
        _handle = System.Diagnostics.Process.GetCurrentProcess().Handle;
        _filestream = System.IO.File.Open(@"c:\temp\TestFile.txt", 
                                          System.IO.FileMode.Open);
    }
        public IntPtr Handle
        {
            get { return _handle; }
        }
        public long FileSize
        {
            get { return _filestream.Length; }
        }
      //notice we have declared this method as private because this is not thread      -safe 
      //and should only be called once. Here we are declaring a global variable        //to ensure it only executes once.
       private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                 {
                    //release managed resources
                    if (_filestream !=null) _filestream.Dispose();
                 }
                 //release unmanaged resources
                 _handle = IntPtr.Zero;
                _disposed = true;
            }
        }
        public void Dispose()
        {
            Dispose(true);
            //don't bother trying to dispose this object.
            GC.SuppressFinalize(this);
        }
       //Create Finalize Method. This will be called by GC to dispose off 
       //unmanaged resources.
       ~Unmanaged()
       {
          Dispose(false);
       }
    }
}

Notice few things that I changed in this class. First, I created a _fileStream object which is a managed resource. Then in Dispose method, I disposed this object along with unmanaged resource i.e. IntPtr. But I also did something else, which is very important when you are disposing managed resources yourself. In ~Unamanged destructor, I am now passing "false" for disposing. Since GC runs in background and doesn't destroy objects in order they were created, it is entirely possible that _filestream object was already destroyed before GC called your version of Finalize method (destructor). You want to make sure that when you manually call Dispose, you dispose off both managed and unmanaged resources (GC couldn't dispose off managed resource then because object is still in use), but if you let GC call your destructor, you shouldn't dispose managed resources since GC may have already disposed it.

Even if you are using managed resources, it is a good practice to dispose off your objects especially if they are large and consume lot of memory (such as collection of images) as soon as your are done using it. But, you must be careful to design your dispose methods in such a way that you don't interfere with GC.

Thank you.

Friday, March 23, 2012

Implementing IDisposable Interface-Part I

In previous posts we discussed ICmparer and IComparable interfaces, today we will discuss another important interface called IDisposable. Before we dive into its implementation, lets refresh our memory on how things were before .NET framework.

Before .NET Framework, if you initialized an object such as opening a database connection, you must manually dispose it. You could eventually bring your system to its knees, if you forgot to dispose your objects.

Framework solved this problem by introducing the concept of Garbage Collector. GC runs on a background thread and uses complex mechanism to determine which initialized objects are no longer being used and can be safely destroyed. It then disposes those objects for you. There is only one caveat - it can only dispose the managed objects i.e. the objects that are part of the .NET Framework library. If you invoke a non managed resource such as an IntPtr to acquire a Windows Handle or some other unmanaged resource (via PInvoke), you are on your own and must dispose them.

Framework provides an IDisposable interface with a Dispose method that you can implement in classes which will initialize and consume unmanaged resources.

Let's see an example.

In this example, we will obtain the handle associated with current process and assign it to a variable of type IntPtr which is unmanaged and must be disposed manually. We will implement Dispose method and then dispose this object.

Unmanaged Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace IDisposableInterface
{
    class Unmanaged:IDisposable
    
    {
        private bool _disposed;
        private IntPtr _handle;

        //initializer method 
        public Unmanaged()
    {
        //we create a new pointer and associate it with the current process
        // This is unmanaged code and _handle must be disposed explicity 
        //and GC will not collect it
         _handle = new IntPtr();
        _handle = System.Diagnostics.Process.GetCurrentProcess().Handle;
    }
        public IntPtr Handle
        {
            get { return _handle; }
        }
      //notice we have declared this method as private because this is not thread-safe 
      //and should only be called once. Here we are declaring a global variable _declared 
        //to ensure it only executes once.
       private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                //release unmanaged resources
                 _handle = IntPtr.Zero;
                _disposed = true;
            }
        }
        public void Dispose()
        {
            Dispose(true);
        }

    }
}


Dispose method is not thread-safe and in a multi-threaded application you must use synclock before calling this method. Also, you cannot dispose an object once it is disposed, so care must be taken to dispose it only once. In above class, we have declared a private Dispose method to ensure we only dispose an object once.

Calling the Dispose Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IDisposableInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            // instantiate unmanaged class and retrieve the handle
            Unmanaged notManaged = new Unmanaged();
            Console.WriteLine("Handle:={0}", notManaged.Handle);
            //Dispose
            notManaged.Dispose();
            Console.Read();
        }
    }
}


Since this is unmanaged code, GC will not dispose it so there are no worries, but if you were using managed code and had implemented your own dispose method, you will have to ensure GC doesn't try to dispose the object that you have already disposed.

We will see how to properly implement your own dispose method for managed code and what may be the advantages of doing so in the next post.

Thank you.



Tuesday, March 20, 2012

Implementing IComparer Interface

We discussed IComparable interface in previous post and touched a bit on IComparer interface. IComparable interface only compares two objects of the same type and the class must implement IComparable interface. But what if you have two different objects that you want to compare, or what if you want to compare the same object, but the class doesn't implement ICmparable interface?

IComparer interface provides additional methods of comparing the objects. For example, we can sort a class based on multiple properties or fields.

This interface implements a method called "Compare()" which takes two object parameters and returns an integer value like "CompareTo()" method.

Let's use the same example like we used in previous post but this time we will use "IComparer" interface.

Order Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableInterface
{
    class Orders
    {
        public int orderID { get; set; }
        public DateTime orderDate { get; set; }
        public int quantity { get; set; }
        public int customerID { get; set; }
        public string customerName { get; set; }
        public Status OrderStatus { get; set; }
           

    }
}

Three classes implementing "Compare" method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableInterface
{
    class OrderCompare:IComparer<Orders>
    {
        
        //you must implement Compare method declared in IComparable interface
        //sort in ascending order
        public int Compare(Orders order1, Orders order2)
        {
            if (order1.orderID > order2.orderID) return 1;
            else if (order1.orderID < order2.orderID) return -1;
            else return 0;
        }

    }
    class OrderCompare2:IComparer<Orders>
    {
        //but you can implement overloaded signature
        //sort in descending order
        public int Compare(Orders order1, Orders order2)
        {
            if (order1.orderID < order2.orderID) return 1;
            else if (order1.orderID > order2.orderID) return -1;
            else return 0;
        }
    }
    class OrderCompare3 : IComparer<Orders>
    {
        //sort by different field - string sort
        public int Compare(Orders order1, Orders order2)
        {
            return string.Compare(order1.customerName,order2.customerName);
        }
    }
}


Using the Sort Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableInterface
{
    class Program
    {
        
        static void Main(string[] args)
        {

            //Let's create a collection of orders and then sort them.
            List<Orders> orderlist = new List<Orders>
            {
                new Orders{orderID=100,orderDate=DateTime.Today,
                           quantity=5,customerID=10,
                           customerName="Second User",OrderStatus=Status.placed},
                new Orders{orderID=90,orderDate=DateTime.Today,
                           quantity=15,customerID=20,
                           customerName="First User",OrderStatus=Status.placed}
            };
            //let's not sort it
            foreach (Orders order in orderlist)
            { Console.WriteLine("Order ID:{0}", order.orderID); }

            Console.WriteLine(Environment.NewLine);

            //now sort using 1st comparer
            Console.WriteLine("Sort Using Order ID - Ascending");
            OrderCompare ordersort = new OrderCompare();
            orderlist.Sort(ordersort);
           foreach (Orders order in orderlist)
            { Console.WriteLine("Order ID:{0}, CustomerName{1} ", 
                                 order.orderID,order.customerName); }

           Console.WriteLine(Environment.NewLine);
           //now sort using end comparer
           Console.WriteLine("Sort Using Order ID - Descending");
           OrderCompare2 ordersort2 = new OrderCompare2();
           orderlist.Sort(ordersort2);
           foreach (Orders order in orderlist)
           { Console.WriteLine("Order ID:{0}, CustomerName{1} ", 
                                order.orderID, order.customerName); }

           Console.WriteLine(Environment.NewLine);
           //now sort using end comparer
           Console.WriteLine("Sort Using Customer Name");
           OrderCompare3 ordersort3 = new OrderCompare3();
           orderlist.Sort(ordersort3);
           foreach (Orders order in orderlist)
           { Console.WriteLine("Order ID:{0}, CustomerName{1} ", 
             order.orderID, order.customerName); }

            Console.Read();

        }
    }
}

Compare method allows you to compare two objects even if they don't implement IComparer interface. You simply pass an instance of the class implementing this interface to the Sort method.

Thank you.

Saturday, March 17, 2012

Implementing IComparable Interface

As we discussed in previous posts, an interface is a contract. A class implementing an interface must implement all the signatures that are declared in this interface.

Why do you need interfaces if all they provide are the method signatures with no actual implementation? One of the reason you implement an interface is to ensure code reuse and standards. By implementing an interface, you can be virtually guaranteed that a class implementing an interface must have implemented its signatures.

For example, suppose you have a car class and a truck class, both implementing an interface IAutoMobile. IAutoMobile has a signature method called "Horsepower". Since both car and truck classes implement IAutomobile, you can be sure both classes will also implement "Horsepower" method.You can write a static method that can accept an object of type IAutoMobile and call the "Horsepower" method. Depending on the object type you passed to this method (class or truck), the code will execute the appropriate "Horsepower" and return you the information.

To see an example of this, see my previous post titled Abstraction via Interfaces - II.

While you can create and implement your own interfaces, .NET provides several interfaces that you can implement  in your classes. Today, we will discuss one such interface "IComparable".

IComparable interface provides a "CompareTo" signature that you can implement in a class to compare the two objects of this type.

Let's consider an example...

Orders Class implementing IComparable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableInterface
{
    class Orders : IComparable
    {
        public int orderID { get; set; }
        public DateTime orderDate { get; set; }
        public int quantity { get; set; }
        public int customerID { get; set; }
        public Status OrderStatus { get; set; }

        //you must implement CompareTo method declared in IComparable interface

        public int CompareTo(object obj)
        {
            //cast the object to its proper type
            Orders order = obj as Orders;
            //OR
            //Orders order = (Orders)obj;
            
            if (this.orderID > order.orderID) return 1;
            else if (this.orderID < order.orderID) return -1;
            else return 0;
        }
        
    }
}


Main Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableInterface
{
    class Program
    {
        static void Main(string[] args)
        {

            //Let's create a collection of orders and then sort them.
            List<Orders> orderlist = new List<Orders>
            {
                new Orders{orderID=100,orderDate=DateTime.Today,quantity=5,
                           customerID=10,OrderStatus=Status.placed},
                new Orders{orderID=90,orderDate=DateTime.Today,quantity=15,
                           customerID=20,OrderStatus=Status.placed}
            };
            //let's not sort it
            foreach (Orders order in orderlist)
            { Console.WriteLine("Order ID:{0}", order.orderID); }

            Console.WriteLine(Environment.NewLine);
            //now sort it
            orderlist.Sort();
            foreach (Orders order in orderlist)
            { Console.WriteLine("Order ID:{0}", order.orderID); }

            Console.Read();

         }
    }
}

Let's review the output before and after the sort. If you look closely, the output before orderlist.Sort() method is in the order objects were added to the collection, but after the Sort(), the objects are listed in ascending order based on the order ID. You may be wondering how come we didn't call the CompareTo method? Actually a Sort() method internally uses CompareTo method to compare the objects based on your implementation. Try the same example but without implementing IComparable interface and you will receive an error.

Output



The CompareTo method in the above example takes a generic object which then must be cast into a specific type. Framework provides another type safe interface "IComparable<>" which you can implement in your classes and no typecasting will be necessary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComparableInterface
{
    class Orders2 : IComparable<Orders2>
    {
        public int orderID { get; set; }
        public DateTime orderDate { get; set; }
        public int quantity { get; set; }
        public int customerID { get; set; }
        public Status OrderStatus { get; set; }

        //you must implement CompareTo method declared in IComparable interface

        public int CompareTo(Orders2 order)
        {
            //not casting necessary

            if (this.orderID > order.orderID) return 1;
            else if (this.orderID < order.orderID) return -1;
            else return 0;
        }
    }
}


IComparable is useful when a class implements this interface and you are comparing the same objects. CompareTo method takes another object which is of the same type and compares the current object to the passed one. But what if your class doesn't implement IComparable or if you want to compare two different objects. Framework provides another interface called IComparer. This interface defines a Compare() method that can take two objects of another type and compares them. We will look at an example of the ICompare interface in future post.

Thank you.

Wednesday, March 14, 2012

Polymorphism via Interfaces - II

In previous post we discussed polymorphism via interface. In this post we will expand it to demonstrate how you can implement more than one interface in a class and how you can pass an object that implements the interface to another method and have it do something.

In the example below, we declared two interfaces - IPrintable and IUserType and then created three classes that will implement these two interfaces. We then declared another static class with a static method that can accept the object and do something with it.

IPrintable Interface
Paste your text here.using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    interface IPrintable
    {
        void print();
    }
}


IUserType Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    interface iUserType
    {
        void userType();
    }
}


First Class - Implementing both Interfaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    class Employee:IPrintable,iUserType
    {
        public string Name { get; set; }
        public bool IsFullTime { get; set; }
        
        public void print()
        {
            Console.WriteLine("Name:={0},FullTime={1}", Name, IsFullTime);
        }
        public void userType()
        {
            Console.WriteLine("Employee");
        }
    }
}


Second Class - Implementing both Interfaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    class Instructor :IPrintable,iUserType
    {
        public string Name { get; set; }
        public string SeniorityLevel { get; set; }
        public bool IsTenured { get; set; }

        public void print()
        {
            Console.WriteLine("Name:={0},SeniorityLevel={1},Tenured={2}", 
                              Name, SeniorityLevel, IsTenured);
        }
        public void userType()
        {
            Console.WriteLine("Instructor");
        }
    }
}



Third Class - Implementing both Intefaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    class Student : IPrintable,iUserType
    {
        public string Name { get; set; }
        public string StudentID { get; set; }
        public String GradeLevel { get; set; }

        public void print()
        {
            Console.WriteLine("Name:={0},GradeLevel={1},StudentID={2}", 
                               Name, GradeLevel, StudentID);
        }
        public void userType()
        {
            Console.WriteLine("Student");
        }
    }
}



Static Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    static class Print
    {
        public static void Printout(IPrintable printableObject)
        {
            printableObject.print();
        }
        public static void UserType(iUserType UserType)
        {
            UserType.userType();
        }
    }
}





Calling Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interfaces
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "1st Employee";
            emp.IsFullTime = true;

            Print.Printout(emp);
            Print.UserType(emp);
            Console.WriteLine(Environment.NewLine);

            Instructor ins = new Instructor();
            ins.Name = "1st Instructor";
            ins.IsTenured = true;

            Print.Printout(ins);
            Print.UserType(ins);
            Console.WriteLine(Environment.NewLine);

            Student std = new Student();
            std.Name = "1st Student";
            std.StudentID = "123456";
            std.GradeLevel = "Junior";

            Print.Printout(std);
            Print.UserType(std);
            Console.Read();

        }
    }
}




In the example above, three classes implement IPrintable and IUserType interface and the Main method calls static methods Printout and UserType declared in Print static class, passing the object.

Notice the Printout and UserType static methods call Print and userType that are implemented in the passed objects.

The only reason you can be sure that regardless of the object type you pass to the static Print and UserType method, the code will work just fine is because any class that implements an interface is guaranteed to implement all the signatures that are declared in the interface. An interface is a contract and any class implementing an interface must implement all its methods.

Sunday, March 11, 2012

Auto Implemented Properties

One of the best practices of object oriented development is to never declare public variables. Instead, you should declare private variables and assign the values and access the values via public properties.

Generally you declare properties this way
private string _name;
public string Name
{
    get{return _name;}
    set{_name=value;}
}

C# 3.0 introduced a short-cut to implement properties. Instead of manually declaring a private variable and public property to set/read values, you can simply declare a public property and compiler will automatically create a private anonymous field that can only be accessed by the get / set accessors of the property. This private field is called backing field. For example, the above property declaration can be accomplished by doing the following...

public string Name { get; set; }

This one line declaration is equivalent to what we declared manually above.

Let's consider an example...

A class with auto implemented properties

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoProperties
{
    class Student
    {

        //You can declare properties like this and C# will 
        //create backing variables to store and read values form
        public string Name{ get;set;}
        public string Address { get; set; }
        public int StudentID { get; set; }

        public void print()
        {
            Console.WriteLine("Name:={0},Address:={1},StudentID:={2}", 
                              Name, Address, StudentID);
            Console.Read();
        }
  }
    
}

Implementing the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            Student std1 = new Student();
            std1.Name = "First Student";
            std1.Address = "123 Roswell Road, Atlanta, GA 30101";
            std1.StudentID = 12345;
            std1.print();
        }
    }
}


Auto implementation is a quick way to implement properties, but there are a few limitations to this approach. You cannot implement different access levels for get and set. When you implement properties this way, both get and set are public and the class is mutable, i.e. outside code can modify the values. You also cannot implement just get, both get and set accessors must be implemented together. Similarly, if you need some code within get or set, you cannot use auto implemented properties.

This is a nice shortcut for simple classes with few properties, however you must use expanded properties declaration if you need something more.

Thank you.


Saturday, March 10, 2012

Polymorphism via Interfaces

In previous post we discussed polymorphism via abstraction. Today, we will discuss polymorphism via interfaces. The concept is similar except that here you declare an interface with a signature which you will then implement in one or more derived class

Consider a base employee interface with signature and then you create a full time and part time employee classes that inherit from this interface.

Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    interface iEmployee
    {
        
        void PrintEmployee();
        
    }
}


Derived Class 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class FullTime : iEmployee
    {
        public int employeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays { get; set; }

        // a method signature declared in interface is implemented here
        void iEmployee.PrintEmployee()           {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}",
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}


Derived Class 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
     class PartTime:iEmployee
    {
        public int employeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       // a method signature declared in interface is implemented here
        void iEmployee.PrintEmployee() 
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
      public void Print()
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }

    }
}



As you can see, a method signature "PrintEmployee" is implemented in derived classes. A class can implement one or more interfaces and must implement the method signatures declared in each interface.

You can use the above classes as follows. Notice since the method PrintEmployee is declared in an interface, you cannot use it like you would if it was declared in a class. Since both PartTime and FullTime implement iEmployee, you should be able to cast the classes to iEmployee and then call PrintEmployee method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class Program
    {
        static void Main(string[] args)
        {
            PartTime Emp1 = new PartTime();
            //notice this property is declared in base class but available in derived class.
            Emp1.employeeID = 1234;
            Emp1.FirstName = "Part Time";
            //notice this property is declared in base class but available in derived class.
            Emp1.LastName = "Employee";
            Emp1.EmployeeType = "Part Time";

            iEmployee Emp = Emp1;
            Emp.PrintEmployee();

            FullTime Emp2 = new FullTime();
            //notice this property is declared in base class but available in derived class.
            Emp2.employeeID = 5678;
            Emp2.FirstName = "Full Time";
            //notice this property is declared in base class but available in derived class.
            Emp2.LastName = "Employee";
            Emp2.EmployeeType = "Full Time";

            Emp = Emp2;
            Emp.PrintEmployee();

            Console.ReadLine();
        }
    }
}

This is a basic concept but interfaces could be confusing. Hope this helps you understand the concept.

Thank you.



Thursday, March 8, 2012

Polymorphism via Abstraction

In previous post we discussed polymorphism via inheritance. Today, we will discuss polymorphism via abstraction. The concept is similar except that here you declare an abstract class as a base class with an abstract method which you will then implement in one or more derived class

Consider a base employee class with few properties and then you create a full time and part time employee classes that inherit from the employee class.

Base Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    abstract class Employee
    {
        
        public abstract void PrintEmployee();
        
    }
}


Derived Class 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class FullTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



Derived Class 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class PartTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



As you can see, base abstract method "PrintEmployee" is implemented in derived classes. You can declare a method signature with keyword abstract or yon can declare a fully implemented method and use it in derived classes.

If you want to implement a method like we did here, you must declare the method with keyword "abstract" in base class and use keyword "override" in derived class.

This is a very basic concept but could be confusing for someone new to object oriented programming paradigm. Hope this helps you understand the concept.

In future post we will discuss polymorphism via interfaces.

Thank you.



Tuesday, March 6, 2012

Polymorphism Via Inheritance

In one of my post  we discussed four basic tenets of Object Oriented Programming. Polymorphism is one of the key fundamental of OOP. Polymorphism means many forms - in other words an object can take on many forms based on its implementation details. There are several ways you can implement polymorphism such as via inheritance, via interface or via abstract classes. We will discuss polymorphism via inheritance today.

Consider a base employee class with few properties and then you create a full time and part time employee classes that inherit from the employee class.

Basically you are declaring a base class with some parameters/features and then extending it into the derived classes by either modifying the base functionality or adding class specific features.

Base Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class Employee
    {
        public int employeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual void PrintEmployee()
        {
            Console.WriteLine("EmployeeID={0},Employee Name={1}, {2}", 
                              employeeID,LastName, FirstName);
            Console.WriteLine(Environment.NewLine);
        }
    }
}


Derived Class 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class FullTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            base.PrintEmployee();
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



Derived Class 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class PartTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            base.PrintEmployee();
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



As you can see, base virtual method "PrintEmployee" is extended in derived classes. Properties declared in the base class are available to derived classes.

If you want to extend a method like we did here, you must declare the method with keyword "virtual" in base class and use keyword "override" in derived class.

This is a very basic concept but could be confusing for someone new to object oriented programming paradigm. Hope this helps you understand the concept.

In future posts we will discuss polymorphism via interface and abstract classes.

Thank you.



Sunday, March 4, 2012

Events in C#

An event allows an object to broadcast a notification that may be of value to other objects listening to this event.

Consider you have a class (caller) monitoring stock market changes (callee). This class calls a method within another class which subscribes to an external service to periodically receive price updates.

One way to implement this would be to have a timer in the caller class which periodically fires, calling the method in the callee class, which then returns the stock prices.

A more elegant solution would be to have the callee fire an event when price changes and caller class to listen to those events. As soon as callee fires an event, caller will get notification and update the stock prices.

Events are useful for one class to broadcast a notification and all client objects listening to these events can do something with it. Events are created and used by using delegates. Review my previous post about delegates to get a better understanding about delegates and their purpose. Delegates are basically wrappers around a method allowing these methods to be called via delegates.

Let's use the above example to see how you can hook up events to get the stock price changes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    //create a delegate
    public delegate void ChangeStockPrice(object sender, EventArgs e);
    
    public class GetStockPrices
    {
         public string _ticker;
         public double _price;

         
         //create an event
         public event ChangeStockPrice PriceUpdated;

        //when ever price changes, raise the PriceUpdated event;
        protected virtual void OnPriceChange(EventArgs e)
           {
                  if (PriceUpdated !=null)
                  PriceUpdated(this, e);
           }

       //create a method to change stock price
        public void ChangePrice(string ticker,double price)
           {
                _ticker=ticker;
                _price = price;
                // fire the event
                OnPriceChange(EventArgs.Empty);
            }
       }
    //create an event listener class
    public class EventListener
   {
     private GetStockPrices stockprice;
     //attach event
    public void Attach(GetStockPrices stock)
     {
         stockprice=stock;
         stockprice.PriceUpdated += new ChangeStockPrice(PriceChanged);
     }
     protected void PriceChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Ticker: {0}, Price: {1}", stockprice._ticker, stockprice._price);
    }
    //you can detach an event
    public void Detatch()
    {
        stockprice.PriceUpdated -= new ChangeStockPrice(PriceChanged);
    }
   }

}

Now let's call the above class which will fire an event showing up the stock price information.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
                   
        static void Main(string[] args)
        {
            
           GetStockPrices stockprice= new GetStockPrices();
            EventListener Listener = new EventListener();
            Listener.Attach( stockprice );
            stockprice.ChangePrice("MSFT",33.50);
            //detatch
            Listener.Detatch();
            Console.Read();
      }
    }
}


Events allow multiple subscribers to subscribe to an event fired by one class, instead of trying to poll the class to see if something change. When you are running multi-threaded applications, the parent thread can fire off another thread and then listen to the object on child thread raising the event once the processing is complete.

Hope this helps in understanding events and how you can use them in your application.

Thank you.

Thursday, March 1, 2012

C# Delegates

The concept of delegates is somewhat confusing and developers often wonder why we need them and where would we use delegates? We will discuss delegates with an example and hopefully clarify potential uses for them.

Consider a list object of a specific type. You can encapsulate one or more objects of the same type in this list and pass the list to other methods to read and do something with those objects. Delegates are similar in nature except that they encapsulate references to the methods of an object.

A delegate can encapsulate any method as long as method signatures are same as those of delegates. Use can then pass around those delegates or use them just as you would use the method encapsulated in those delegates.

Let's consider an example.

In this example, we will create a class which will take the hourly pay, hours worked, tax rate and return weekly pay as well as tax.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class CalculateWeeklyPay
    {
        private double _hourlypay;
        private double _hours;
        private double _overtimerate;
        private double _taxrate;

   public CalculateWeeklyPay(double hourlypay, double hours, 
                             double overtime, double taxrate)
        {
            _hourlypay = hourlypay;
            _hours = hours;
            _overtimerate = overtime;
            _taxrate = taxrate;
        }
        public double calculateTax()
        {
            double grosspay = calculateGrossPay();
            double tax = grosspay * ((double)_taxrate / 100);
            return tax;
        }
  public double calculatePay(double hourlypay, double hours, 
                             double overtime, double taxrate)
        {
            _hourlypay = hourlypay;
            _hours = hours;
            _overtimerate = overtime;
            _taxrate = taxrate; 
            return calculatepay();
        }
        public double calculatePay()
        {
            return calculatepay();
         }
        private double calculatepay()
        {
            double grosspay = calculateGrossPay();
            double netpay = grosspay-(grosspay * ((double)_taxrate / 100));
            return netpay;
        }
        private double calculateGrossPay()
        {
            double basepay;
            double overtimepay = 0;
            double grosspay;
            
            if (_hours > 40)
            {
                overtimepay = (_hours - 40) * (_hourlypay * _overtimerate);
                basepay = 40 * _hourlypay;
            }
            else
            {
                basepay = _hours * _hourlypay;
            }
            grosspay = basepay + overtimepay;
            return grosspay;
        }
     }
}

Now, lets create a console app, which will instantiate this object and then return the weekly pay and tax. We will create two delegates. One delegate will work with two methods (CalculatePay and CalculateTax) and another delegate will work with overloaded CalculatePay method.

Note, a delegate must have the same signature and same return type of the referenced method that it will encapsulate.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        //declared two deletages, one for each method
        //(since they have different signatures, you can't use same delegate)
        //also note return type for the delegate 
        //must be same as the return type of the signature.
        public delegate double delegate1();
        public delegate double delegate2(double hourlypay, double hours, 
                                         double overtime, double taxrate);
      
           
        static void Main(string[] args)
        {
            double hourlyPay = 7.50;
            double hours = 45;
            double overtimeRate = 1.5;
            double taxRate = 5;
          CalculateWeeklyPay calculatepay = new CalculateWeeklyPay(hourlyPay, 
                                                 hours, overtimeRate, taxRate);
            //you must instantiate a delegate
            delegate1 firstDelegate = new delegate1(calculatepay.calculatePay);
            Console.WriteLine("First Delegate {0} ", firstDelegate());
            Console.WriteLine(Environment.NewLine);
            //you can use same delegate for another method as long as 
            //its signatures and return type are same
            delegate1 anotherDelegate = new delegate1(calculatepay.calculateTax);
            Console.WriteLine("First Delegate Different Use {0} ", 
                              anotherDelegate());
            Console.WriteLine(Environment.NewLine);
            //let's use second delegate
            delegate2 secondDelegate = new delegate2(calculatepay.calculatePay);
            //you must pass the parameters that this delegate is expecting, 
            //otherwise a runtime error will occur
            Console.WriteLine("Second Delegate{0} ", 
                       secondDelegate(hourlyPay, hours, overtimeRate, taxRate));
            Console.WriteLine(Environment.NewLine);
            Console.Read();
        }
    }
}


One of the main use of delegates is in events. Suppose you want an object to notify another object when something happens. For example, a stock market object should fire an event when stock price changes for a stock you are watching. Another object (listener) can capture this event and do something with it instead of constantly polling the stock market object to see if the price has changed. In C#, you need delegates to create events such as this.

We will discuss events in future posts.

Thank you.