Showing posts with label Better Programming. Show all posts
Showing posts with label Better Programming. Show all posts

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.

Sunday, February 26, 2012

Arrays and Arraylist in .NET

So far we have been discussing the fundamentals of object oriented programming, difference between interfaces, abstract classes, enumerations, structures etc. Today, we will talk about using arrays and arraylists to store various objects and difference between the two.

Both arrays and arraylists are stored on a heap. Even if you store value types in an array or an arraylist, the values are implicitly converted to reference types (boxing) and you must explicitly convert them back to proper value types (unboxing) when using them.

Since the items stored in an array or an array list are objects, you can use them to also store reference to objects. For example,

consider the following class...

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

namespace ConsoleApp1
{
    class Student
    {
      
     private string _name;
     private string _address;
     private int _studentID;
     public string Name
     {
          get {return _name;}
          set {_name=value;}
     }
     public string Address
     {
          get {return _address;}
          set {_address=value;}
     }
     public int StudentID
     {
          get {return _studentID;}
          set {_studentID=value;}
     }
  }
    
}

Now let's use an array to store several references of these objects.

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using an Array
 
            //first instance
             Student student1 = new Student();
             student1.Name = "Student One";
             student1.Address = "123, Peachtree Road, Atlanta, GA 30303";
             student1.StudentID = 1;
            //second instance
             Student student2 = new Student();
             student2.Name = "Student Two";
             student2.Address = "456, Peachtree Road, Atlanta, GA 30303";
             student2.StudentID = 2;
            //third instance
             Student student3 = new Student();
             student3.Name = "Student Three";
             student3.Address = "678, Peachtree Road, Atlanta, GA 30303";
             student3.StudentID = 3;

             //instantiate an array to store these objects.
             Student[] StudentsList = new Student[2];
             StudentsList[0] = student1;
             StudentsList[1] = student2;
             StudentsList[2] = student3;

            //since array is already of type Student, no typecasting is necessary.
            Console.WriteLine(StudentsList[0]);

       }
    }
}

There are several problems with this approach. First, you have to initialize an array and specify its size. Which means you have to know how many objects you are going to store in an array beforehand. Second limitation is that an array must be specific to the type you are going to store, meaning you cannot store two different types of objects in an array. Also, once an array has been initialized to a specific size, you cannot resize it downwards.

Now let's consider the same example using an arraylist.

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
             
            //first instance
             Student student1 = new Student();
             student1.Name = "Student One";
             student1.Address = "123, Peachtree Road, Atlanta, GA 30303";
             student1.StudentID = 1;
            //second instance
             Student student2 = new Student();
             student2.Name = "Student Two";
             student2.Address = "456, Peachtree Road, Atlanta, GA 30303";
             student2.StudentID = 2;
            //third instance
             Student student3 = new Student();
             student3.Name = "Student Three";
             student3.Address = "678, Peachtree Road, Atlanta, GA 30303";
             student3.StudentID = 3;

            //instantiate an arraylist to store these objects.
             ArrayList StudentList = new ArrayList();   
            
            // notice an arraylist isn't of a specifc type.
             StudentList.Add(student1);
             StudentList.Add(student2);
             StudentList.Add(student3);

            //since arraylist is a generic list, you must type cast it first.
            Console.WriteLine((Student)(StudentList[0]));

            //Arraylist allows for inserting an object at a specific position.

             //fourth instance
             Student student4 = new Student();
             student4.Name = "Student Four";
             student4.Address = "890, Peachtree Road, Atlanta, GA 30303";
             student4.StudentID = 4;
             StudentList.Insert(1, student4);

            //You can also remove an object from an array list
             StudentList.Remove(student4); // remove a specific object
            //OR
             StudentList.RemoveAt(2);   //remove whatever is at index 2
     
        }
    }
}

As you can see, an arraylist avoids some of the problems of an array. First, an arraylist doesn't have to be sized and resized. An element can be added or removed from an arraylist.

Note, since an arraylist isn't cast into a specific type during declaration, when reading the content from an arraylist, you must explicitly cast to a specific type, as show in the above code snippet.

An arraylist also allows for inserting an object at any position, including the position where an object may already exist. If you insert an element at a position already occupied by another element, the current element will simply push down.

Since an arraylist isn't of a particular type, you can add elements of reference or value types in an array, even mixing them.

For example you can do the following.

StudentList[0] = student1;
StudentList[1] = 5;
StudentList[2] = "This is a test";
StudentList[3] = student2;

But if you add objects of different types or value types in the same arraylist, you must first inspect the element to determine its type before casting it to the appropriate type. This is not only cumbersome and error prone, it also adds an unnecessary overhead.

To write out the content from the above example, you now have to do the following...

if (StudentList[1].GetType() == typeof(int))
   {
    //do something
   }

This becomes unusable pretty quickly. So, what should you do to get the flexibility of an arraylist without the added overhead? In the next post we will talk about generic collections and how they can aid us in a situation like this.

Friday, February 24, 2012

Structures in .NET

As we discussed in previous post, enumerations and structures are two complex types that are value types. Structures allow you encapsulate certain data elements similar to a class, except that structures are value types while classes are reference types.

Structures are very similar to classes with few differences.
  • Unlike classes, structures cannot inherit from other structures or a class, although they can implement interfaces.
    • Since they cannot inherit from other structures, an structure cannot be a base structure, which means structure members cannot be declared as "Protected".
  • Similar to classes, structures can have constructors, properties, methods etc.
  • Unlike classes, you cannot declare a parameterless constructor in a structure, although you can declare overloaded constructors with parameters. Strucutres always have a default constructor.
  • Unlike classes, you can instantiate an structure without using "new" operator.
Structures are suitable when you want to implement lightweight objects such as a point or color or a rectangle etc. 

Let's see an example in action...

    using System;
    struct StructExample
    {
        private int _width;
        private int _height;
   
        public int Width
        {
            get { return _width;}
            set {_width = value;}
         }

       public int Height
      {
           get { return _height;}
           set {_height = value;}
      }
   }


Let's use this structure

    Using System;
    class TestStructure
    {
       static void Main()
       {
             StructExample example1 = new StructExample();
             example1.Width  =1;
             example2.Height = 3;
             Console.WriteLine(example1.Width + ' ' + example1.Height);
             Console.Read();
        }
    }

As I mentioned previously, you should only use structures for lightweight objects because they are value types and are stored on a stack. Also, since they are not reference type, you are directly dealing with the structure and not with a reference, like you would with a class.

Thank you.








Wednesday, February 22, 2012

Enumerations

Recall my previous post about value types vs. reference types. Just to recap, simple data types such as int, float, double, decimal etc. are value types while complex types such as objects, strings are reference types. There are two exceptions to this concept. Structures and Enumerations. Despite being complex types, Structures and Enumerators are value types and hence they are stored on stack as opposed to heap.

In this post we will discuss enumerations and we will cover structures in next post.

Enumerations
Enumerations allow you to group constants at one place in a name-value pair format and allows you to access the values using strongly typed names. The key difference between an array list or a dictionary object and enumeration is that the arraylist / dictionary is a reference type and hence stored on heap while enumerators are value types and are stored on stack. Use of enumerators also allow you to keep the constants at one place hence being able to easily manage them and makes your code easier to read.

The underlying datatype for an enumeration can only be of an integral type. It can be of any integral type except "Char". The default type is int.

An enumeration is declared using enum keyword. Lets see an example.

enum Color
{
   Red,
   Blue,
   Green,
   Orange
}

If you don't specify the value, underlying integer datatype is assumed and the value is assigned from 0 onwards. For example in above example, Red=0, Blue=1, Green=2, Orange=3.

You can explicitly assign any value to each type, for example

enum Color
{
   Red = 8,
   Blue = 9,
   Green  =12,
   Orange=20
}


As I mentioned previously, underlying datatype for an enum can be any integral type except char. Following datatypes are supported 
  • byte, sbyte, short, ushort, int, uint, long or ulong.
To use any other datatype except int, declare it as follows...


enum Color : byte
{
   Red ,
   Blue ,
   Green ,
   Orange
}

Usage
Apart from keeping the constants at one place, it also makes code easier to read. See the following example...

 public class EnumTest
 {
   static void Main()
   {
      Console.WriteLine("Red={0}", Color.Red);
      Console.WriteLine("Blue={0}", Color.Blue);
   }
}

That's all there is to it. It is a relatively simple concept but when used appropriately promotes cleaner and readable code.

Thank you.

Friday, February 17, 2012

Generics in .NET Framework

If you came from C++ and worked on a VB 6.0 application, one thing that stood out like a sore thumb was the lack of templates. Templates in C++ allowed for type-safety and code re-usability. In VB 6.0 and in earlier versions of .NET Framework (1.0 and 1.1), you did something like this

Public Sub Add(ByVal param1 As Object, ByVal param2 As Object)

      If TypeOf(param1) = GetType(String) AND TypeOf(param2) = GetType(string) Then

              console.writeline("String=" & param1.ToString & param2.ToString)

      Else If TypeOf(param1) = GetType(int) AND TypeOf(param2) = GetType(int) Then

             console.writeline("Integer=" & DirectCast(param1,int) + DirectCast(param2,int)

      End If

End Sub

Note - C# also suffered from same limitation in 1.0 and 1.1

Aside from all the typecasting, there is something else going on here. Recall from my previous post about boxing and unboxing. If you passed integer values to this method, the passed values will be boxed and then DirectCast will unbox these values since integer is a value type.

Although this provided you flexibility in the sense that you didn't have to write two separate methods - one for numeric operation and one for string operation, it came at a performance cost.

Even if you avoided methods like these, using an arraylist with value types will result in boxing/unboxing as well (recall an example in previous post).

.NET 2.0 introduced the concept of generics. Generics allow you to define a type-safe method, class or structure without committing to a specific data type. You can write code that is just as flexible as the above example, promotes code re-use without the performance degradation of boxing / unboxing.

 Lets consider an example. Assume you want to use the flexibility of an arraylist but without its drawbacks, you can create a generic list object that framework will convert to a passed data-type during compile time.


List<int> Test = new List<int>();     //a list of type int
Test.Add(1);     //no boxing
Test.Add(2);
Test.Add("A");    //compile time error - type safe


Generic Method



void Add<T>(ref T param1)
       {
           T results;
           results = param1;
           Console.WriteLine(results);
       }


You can also declare a generic class or a structure.


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


namespace GenericTest
{
    class GenericList<T>
    {
        void AddToList(T input) { }
    }
}



//Test Generic Class

GenericList<int> list1 = new GenericList<int>(); // list of type int
GenericList<string> list2 = new GenericList<string>(); // list of type string


As I previously mentioned, Generics allow for code re-use without compromising performance. Generics was perhaps one of the most powerful enhancement in .NET Framework 2.0.

As always, your comments are welcome.



Wednesday, February 15, 2012

Boxing and Unboxing

In previous post we discussed the concept of value types vs. reference types and how two are different. Today we will discuss Boxing and Unboxing.

Boxing and Unboxing
Boxing is the process of converting a value type to a reference type. If you recall from my previous post about Value Types vs. Reference Types, the value types are stored on a stack while the reference types are stored on heap and a pointer to the reference type is stored on the stack.

Let's assume you have the following method..


public void Add(object obj, object obj2)
        {
            if (obj.GetType()  == typeof(string) && obj2.GetType() == typeof(string))
                {
                //do something...
                }
            else if (obj.GetType() == typeof(int) && obj2.GetType() ==typeof(int))
                {
                //do something...
                }
        }

 
When you call this method and pass an integer or some other value type variable, it is first boxed, i.e. converted to a reference type and then it is unboxed i.e. converted back to value type before it is used. Boxing is implicit but unboxing is explicit i.e. you must cast the boxed variable back into the value type before you can use it.

Note: The code above is for illustration only and you should try to avoid boxing/unboxing for obvious performance reasons.

Another example of implicit boxing is in the use of an arraylist. For example,

ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);

Recall that an arraylist is a reference type. When you add an integer to the arraylist, it is then boxed i.e. converted to a reference type and then added to the arraylist. When you need to use the value assigned to this arraylist, it must be unboxed.

int i = (int)(list(0);



Tuesday, February 14, 2012

Value Types Vs Reference Types in .NET


Before we dive into the value types or reference types definition, let's take a step back and understand what happens when you declare a variable .NET.

Anytime you declare a variable, some memory is allocated to this variable. There are three pieces of information that is stored in memory - the variable name, its datatype and the value it contains. The variable is stored on one of the two types of memory - Stack and Heap.

When you declare a variable which is of value type (I know I am jumping ahead), some memory is allocated. When you declare another variable of the value type, another chunk of memory is allocated which is stacked on top of the first allocation and so forth. Think of stacks as just boxes stacked on top of one another. For value types the memory is allocated statically. For example, 4 bytes of memory is allocated to a variable of type Int.

Memory is allocated on a first come first serve basis but it is de-allocated in the reverse order i.e. Last In First Out (LIFO). Think of it as you are stacking boxes on top of each other and to remove them, you have to remove the last one first and so on.

When you create a variable of type reference, the object itself is allocated on another type of memory called "Heap". Just as the name suggests, heap is just a collection of reference type variables (also commonly called objects) and there is no particular order. A pointer to these reference type variables is stored on stack.

Memory De-Allocation
When you exit a method or a class where you instantiated and consumed these variables, memory is de-allocated in the following fashion

  • Stack is cleared first in LIFO order.
  • Heap is not cleared - Garbage Collector will clear it at some point
You may be wondering why value types are stored on stack and reference types are stored on heap?

The reason primarily has to do with the complexity. Value types are primitive data types such as Integer, Byte, SByte etc. and framework knows in advance how much memory to allocate when they are initialized. Reference types such as objects on the other hand are complex types. An object may have an instance of another object etc. which means the memory must be dynamically allocated, hence they are stored on a heap.

Another point to note is that all variables must be declared and instantiated, but .NET framework automatically instantiates the value types.

For example - 
int i = new int(5);  
can also be declared as int i = 5;

All reference types with the exception of String must be explicitly instantiated (unless your classes are declared as static/shared).

For example
Person clsPerson = new Person();

Value Types
  • All Numeric Data Types 
    • E.g. integer, byte, sbyte, short, Decimal, Double etc.
  • Variables of type Boolean, Char and Date
  • Enumerations
    • Since the underlying types for enumerators can only be of value type.
  • Structs / Structures
Reference Types
  • String
  • Arrays (even if their elements are value types)
  • Classes / Forms.
  • Delegates

In the future post we will discuss the concept of boxing and unboxing and the difference between structures and classes and performance impacts of using one over the other.

Thank you and as always, your comments are welcome!




Monday, February 13, 2012

Difference between an Interface and an Abstract class

All Programming Fundamentals! It is rather easy to articulate the difference between the two, but I have seen people stumble when asked to explain it. So today, we will try to cover this topic and provide an example to clarify some of the key differences.

 Abstract Class
An Abstract Class is just like any other class with a few key differences. As we discussed in my previous post, non-static classes can be instantiated except with one type of class - an Abstract Class. In other words, an abstract class is one that cannot be instantiated and can only be used as a parent class in other derived (concrete) classes. Since this class cannot be instantiated and you cannot use a non-static class without instantiating it, you cannot use the abstract class by itself. You must inherit from it in other class(es) to use it.

An abstract class may have one or more methods that are completely implemented but it must have at least one abstract method that must be implemented in the derived class(es). This is what makes the abstract class - abstract.

So, in a nutshell an abstract class is just like any other class except that it cannot be instantiated and must have one or more abstract (unimplemented) methods.

Interface
An Interface is not a class. It is a contract and all classes that implement the interface must implement all the properties/methods declared in an Interface.

Unlike an abstract class, an interface cannot have actual implementation of any property/method and also all the properties / methods must be declared public.

Since an interface cannot have any implementation, all the classes inheriting this interface must implement all the methods defined in the interface. Abstract class on the other hand can have fully implemented methods and derived classes can simply use that implementation.

If an abstract class has all the methods defined as abstracts, then both Interface and Abstract class is the same.

Why would you use one over the other?

Both interfaces and abstract classes are good if you want to keep the same structure in your classes inheriting from it. But abstract class allows you to implement one or more common method that can be used as is by all the classes. One advantage that interface have over abstract class is that at least in C# and VB.NET (also true in Java but not in C++) a class can only inherit from one class, while it can implement multiple interfaces.

Interfaces are generally used to define the abilities of a class i.e. what a class can do. For example - IComparable interface. This interface defines "Compare To" signature which can be implemented in the class to compare the instance of an object with another object of the same type. Any class that implements IComparable interface must be capable of doing so.

Abstract classes on the other hand generally implement or define the core capability of the class. For example a MemoryStream class can inherit from a Stream abstract class that implements a Serialize method to serialize the content.

You generally want to use interface if various classes only share certain features, although they may be of different type. For example, a class called Car and a class called Plane may implement the same IMovable interface. You want to use an abstract class when both classes are of same or similar kind. For example a class "BMW" and a class "Lexus" can inherit from the same abstract class called "Car".

If you modify an interface and add a new method, you must modify all the classes implementing that interface to implement that method. You can however modify an abstract class and as long as you fully implement a new method, you don't have to touch other classes inheriting from it.

Let's see both Interface and Abstract class in action.

Abstract Class

Using System;
namespace AbstractInterface
{
    public abstract class Student  
           // notice keyword abstract. In VB.NET the equivalent keyword is MustInherit
     { 
        protected string studentnum;     //protected variables
        protected string studentname;


      public abstract String StudentNumber 
              // notice the keyword abstract. The property is not fully implemented.
           {
             get;
             set;
           }
      public abstract String StudentName
        {
           get;
           set;
        }
     public String GetStudentInfo() // notice this method is fully implemented
      {
        return "Student Number: " + studentnum + " Name: " + studentname;
      }
     public abstract String EnrollmentStatus(); // notice this method is not implemented.


    }
}
   
Concrete Class


using system;
namespace AbstractInterface
{
    public class GraduateStudent : Student // this class inherits from Student class.
   {
     public GraduateStudent()   //constructor
      {
       }
      public override String StudentNumber
           // remember abstract class didn't implement this property so we have to implement it here.
           //   Notice keyword override
        {
           get
            {
               return studentnum;
            }
            set
            {
               studentnum = value;
            }
        }
        public override String StudentName
         
        {
           get
            {
               return studentname;
            }
            set
            {
               studentname = value;
            }
        }


      public new String GetStudentInfo() // this method is implemented in base class.
      {
        return base.GetStudentInfo();
      }


    }
    public override String  EnrollmentStatus () // notice this method is not implemented in base class


      {
        return studentname + " is enrolled."
      }


    }
}

Now lets see an Interface Example

Interface


Public interface IStudent // As a convention, interfaces are prefixed with "I"
{


 String StudentNumber
              // No need to specific "public" since interface can only have public properties/methods.
           {
             get;
             set;
           }
      String StudentName
        {
           get;
           set;
        }
     String GetStudentInfo();
     
     String EnrollmentStatus();
   
          // notice no implementation of any method or property
   }

Concrete Class using Interface


using system;
namespace AbstractInterface
{
     public class Student2 : IStudent    // implements interface


      protected string studentnum;     //protected variables
      protected string studentname;


     public  Student2  ()   //constructor
        {
        }
      public String StudentNumber
           // must be implemented here, otherwise compiler will throw error.
         
        {
           get
            {
               return studentnum;
            }
            set
            {
               studentnum = value;
            }
        }
        public String StudentName
       
        {
           get
            {
               return studentname;
            }
            set
            {
               studentname = value;
            }
        }


      public String GetStudentInfo() // implemented here
      {
        return "Student Number: " + studentnum + " Name: " + studentname;
      }


    }
    public String  EnrollmentStatus ()


      {
        return studentname + " is enrolled."
      }


   // notice - all properties and methods declared in interface must be implemented. Every class inheriting       //from this interface must implement all of them.


    }


}

Hopefully this will help clarify some of the differences between an Interface and an Abstract class. As always, your comments are welcome.

Wednesday, February 8, 2012

Classes and Objects in Object Oriented Programming

All Programming Fundamentals! In my previous post, I wrote about four principles of Object Oriented Programming. Today, we will take it one step further and discuss the concept of a Class and an Object. We will also discuss types of classes.

Class is a template that exhibit certain characteristics. For example, blueprint of a house defines the number of rooms, doors, room size etc. You can use this blueprint to build one or more houses. Similarly, class is a blueprint that can be used to build objects. Each class must have a name, one or more attributes or properties, one or more methods that can be used to perform operations on the object(s) created from this class. For example, A class called "Student" may have the following format.

Class Name
Properties
Methods

An object is an instance of the class. In your application, you can declare an instance of the class and assign it to a variable which will then allow you to access the public properties to read or set the values and use the public methods to perform operations. 

We will talk more about the Public vs. Private vs. Protected Properties/Methods in future post, but for now just remember that any object can access public methods and properties of another object (there are some caveats to it, such as they must be in the same assembly or the consuming object's assembly must reference the assembly where the object resides and they must be imported in the class either by Imports or Using statement on top of the class - more on that later).

Some classes don't need to be instantiated before they can be used. Their public methods and properties are always available without having to instantiate and create an object. I guess you could say that your application automatically creates an instance of the class for all other classes to use.

Remember, while you can have many instances of the class that can be instantiated and one instance will not share the other instance. For example, you can have two instances (objects) of "Student" class called "Student 1" and "Student 2". The properties of "Student 1" will be different than that of "Student 2". Classes that can't be instantiated by definition only have one instance hence only one set of properties.

In C#,  a class declared with STATIC keyword cannot be instantiated. In VB.NET, you don't have a shared class per se, but a Module is closest to the static class. 

In a static class, all methods must be declared static. However a non-static class can have both static and non-static members. Static members will be available regardless of whether the class is instantiated and only one copy of static member will exist, while there can be multiple instances of non-static members. In VB.NET, you can declare methods with keyword SHARED  which will have the same behavior as STATIC in C#.

Constructors
Constructors allows non-static classes to be instantiated. In VB.NET, the constructor is declared as a Public Sub New. In C#, the constructor is same name as the class name. You can have more than one constructor per class. (See example below)


Example:

C#
using System;
namespace 6thGrade
{
public class Student
{
   private int _age;
   private string _name;

   // Default constructor:
   public Student() 
   {
      _name = "N/A";    // assigning a value "N/A" to private string variable name.
   }

   // Another Constructor:
   public Student(string name, int age) 
   {
      this._name = name; // assigning a value passed to the constructor to variable name.
      this._age = age;  // assigning a value passed to the constructor to variable age.
   }

   // Printing method:
   public void PrintStudent() 
   {
      Console.WriteLine("{0}, {1} years old.", name, age);
   }
}
}

VB.NET

Imports System
Namespace 6thGrade
Public Class Student

     Private _age As Int32
     Private _name As String

    Public Sub New()     // default constructor
          name="N/A"
    End Sub
    
    Public Sub New(ByVal name As String, ByVal age As Int32)
          _name=name
          _age=age
    End Sub
    
    Public Sub PrintStudent()
       Console.Writeline(name + ", " + age)
    End Sub
End Class
End Namespace

STATIC CLASS 

C#
using System;
namespace 6thGrade
{
public static class Student
{
   private int _age;
   private string _name;

  //static method
public static void studentinfo(string name, int age)
{
_name=name;
_age = age;
}

   // Printing method:
   public static void PrintStudent() 
   {
      Console.WriteLine("{0}, {1} years old.", name, age);
   }
}
}

VB.NET

Imports System
Namespace 6thGrade
Public Class Student                          // No Static equivalent in VB.NET

     Private _age As Int32
     Private _name As String

    Public Sub New()     // default constructor
          name="N/A"
    End Sub
    
Public Shared Sub studentinfo(ByVal name As String, ByVal age As Int32)
{
_name=name
_age = age
}
Public Shared Sub PrintStudent()
       Console.Writeline(name + ", " + age)
    End Sub
End Class
End Namespace

We will talk more about classes and associations, compositions, property/method accessibility etc in subsequent posts.

Thank you and as always, your comments are welcome!


Tuesday, February 7, 2012

Fundamentals of Object Oriented Programming

All Programming Fundamentals!
Any interview I have been in, either as a interviewer or interviewee, a question about Object Oriented Programming has always come up. Almost always the question is stated as follows...
What are the basic principles of Object Oriented Programming or what are the tenets of Object Oriented Programming.
The answers vary from person to person. Most of the developers with some experience in OOP know what they were talking about, but struggle in putting their answers in words. So, I decided to go ahead and describe what I understand them to be. Keep in mind, these are not the only definitions.
Basically in a nutshell, there are four basic tenets or core principles of Object Oriented Programming.
    • Abstraction
    • Data Encapsulation
    • Inheritance
    • Polymorphism
Abstraction
Abstraction allows for simplicity. As a consumer you do not need to worry about all the implementation details that go in whatever it is you are consuming. For example, when you turn the radio in your car, you mainly care about volume, channel, and a few other items. You don't need to worry about how the radio works and receives the programming over the air. In the world of programming, abstraction is a similar concept. A class could be implemented in various ways, but the consuming application doesn't have to worry about all the intricate details. All the consumer has to know is the public face of the class to use that class and get the expected results back. For example, if you want to generate an invoice for a customer at the end of the month, you will simply pass on customer information, invoice period and expect the class to return you the results back. How the class gathers the data, communicates with other classes or database etc. is of no concern to you.
Abstraction allows for modular code development and code reuse. Same class can be used by various calling methods without having to worry about the class and its implementation details.
Data Encapsulation
Data Encapsulation is simply what the name suggests. All the relevant data is encapsulated within the class. The calling object never has to worry about how the data is manipulated within the callee, only that the data is returned back in the format it was expected. Encapsulation is implemented by classifying certain properties and methods as public and the outside world can only communicate via only those public methods/properties. For example, in an Employee class, you may declare a public property called "Employee Name" as of type String. The caller will expect and will get a string back. How the Employee class assembles the Employee Name to return back to the caller is of no concern to the caller.
Inheritance
Inheritance allows for abstracting certain common characteristics of an entity in a way that multiple entities that exhibit those same characteristics can "inherit" from the common entity without having to declare them. Inheritance is a "Type Of" or "Kind Of" relationship. For example, An Audi is a type of Car. A BMW is a type of Car. A male and a female are a "Type Of" person. Basically what that means is that both Audi and BMW will exhibit certain common characteristics that all cars have. Similarly both male and feamle will exhibit certain characteristics that are common to all persons.
With this understanding, we can define a class called "Car" and a class called "Person" and have "Audi" and "BMW" classes inherit from "Car" and "Male" and "Female" classes inherit from "Person" class. This will allow us to promote some properties to higher level classes that would otherwise have to be defined in each class.
Polymorphism
Polymorphism, when used correctly enables tremendous code reuse. Polymorphism can be used at the class/object level or at the method level. The most common use I have seen is at the method level. At the method level, it manifests itself either in method overriding or method overloading. Method overloading means you can create two or more methods with the same name but with different signature. Method Overriding means you can declare a method in a base class, make it overridable and then override it in individual classes that inherit from the base class. Method Overloading is also called compile time polymorphism because compiler determines which overloaded method to use during compile time. Method Overriding is also called run time polymorphism because which method will be used is determined at run time.
Object level or inheritance level polymorphims occurs when a method is implemented in base class and all the derived classes use the same implementation. For example, you are writing a stream to either file or memory or network location. All the various stream options are implemented in their own class, but they all inherit from the base class called "Stream" and "Serialize" method is implemented in this base class. All the derived classes will be able to use the same "Serialize" method without having to create their own.
There is much more to Object Oriented Programming and indeed even to these 4 basic tenets, but hopefully this will help you get started!

We will be discussing more about Object Oriented Fundamental in the future.
Thank you and your comments are welcome!