Monday, April 21, 2014

Understanding Interfaces

      This is one of the topics in programming languages that we (programmers) get to "fairly" understand after a good experience. I remember my initial months in programming when I knew what is an interface, how it is different from an abstract class, etc. etc. But it always left me wondering, why "really" do we need interfaces? I could not give myself a good justification of the need for interfaces. I just knew the "what" part of it. But "why" part was absolutely missing.


I hope this blog will help few of our friends who are still trying to understand this concept. Let's understand this topic in a question-answer format.


A. What is an interface?

Simply put, interface is a contract. An interface defines a contract, that needs to be fulfilled by classes that implements it.

Now, what is a contract? 
        Contract is a set of properties, methods, events or indexers defined in an interface. If a class implements an interface, the contract is to implement the members defined in the interface. Its a must to implement all of them. If not, c# would give a compile time error.

Compile time errors are actually good. Obviously it's better to get issues at compile time than run time. 

* All interface members have to be public.


B. Why use interfaces?

     Let's understand this with following scenario.
      An application is being designed. The basic requirement is, that the application should be able to connect to any Database in the market.
      In order to understand why use interface, let's see what problems we face if we do not use interfaces. For simplicity and to concentrate on the real problem the example has no way to get a connectionstring.

Solution-1 : Using Concrete class
using System;

namespace Interfaces.ConcreteClassExample
{
    public class Database
    {
        public virtual void OpenConnection()
        {
            throw new NotImplementedException();
        }
    }
}

namespace Interfaces.ConcreteClassExample
{
    class MicrosoftSQLServer : Database
    {
     
    }
}


namespace Interfaces.ConcreteClassExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MicrosoftSQLServer MyServer = new MicrosoftSQLServer();
            MyServer.OpenConnection();
        }
    }
}
The above solution, just leads to a run-time exception! That's the disadvantage of using concrete class in this scenario. There is no contract and so no compile time exception even if a basic implementation is missed out.

Solution-2 : Using Abstract class

Abstract class has members that are declared but not implemented. Those are implemented by the child classes that inherit from the abstract class.


namespace Interfaces.AbstractClass
{
    public abstract class Database
    {
        public abstract void OpenConnection();
    }
}


namespace Interfaces.AbstractClass
{
    public class MicrosoftSQLServer : Database
    {
        public void WelcomeMessage()
        {
            Console.WriteLine("Hello!!");
        }

    }
}


namespace Interfaces.AbstractClass
{
    class Program
    {
        static void Main(string[] args)
        {
            MicrosoftSQLServer MyServer = new MicrosoftSQLServer();
            MyServer.WelcomeMessage();
            Console.ReadLine();
        }
    }
}



In the above example, we get a compile time exception. The compiler is forcing us to implement to OpenConnection method. This is definately better than a run time exception!

Solution-3 : Using Interface

Interfaces are constructs that only have method declaration and no implementation of any method at all. They are similar to a pure abstract classes that too have no implementation.

namespace Interfaces
{
    interface IDatabase
    {
        void OpenConnection();
    }
}


namespace Interfaces
{
    class MicrosoftSQLServer : IDatabase
    {
        //public void OpenConnection()
        //{
        //    Console.WriteLine("Connecting to database...");
        //}
        public void WelcomeMessage()
        {
            Console.WriteLine("Welcome to c# programming fundamentals");
        }
    }
}


namespace Interfaces.AbstractClass
{
    class Program
    {
        static void Main(string[] args)
        {
            MicrosoftSQLServer MyServer = new MicrosoftSQLServer();
            MyServer.WelcomeMessage();
            Console.ReadLine();
        }
    }
}

Output




Similar to abstract classes, interfaces too if not implemented give a compile time exception. The compiler is forcing us to implement all the methods declared in an interface. As mentioned before, interface is a contract to implement all the members.


Conclusion 
     Its better to have compile time exception by using Abstract class or interfaces. That leaves us with a question...What to choose abstract class or an interface? To help make that decision, one has to know the restrictions and advantages of each of them. The next blog on differences between abstract classes and interfaces will help one choose based on needs! 



Static Methods

Static methods, can only be accessed by Class because those are not instance level methods.Refer to the highlighted text in the code below. In order to access static methods the syntax is <ClassName>.<methodName>

When to use? Static methods are good for utility methods that do not depend on a particular instance.

using System;

namespace StaticDataExample
{

    class Car
    {
        public static int nbrOfWheels = 4;
        public string color, typeOfCar;

        public Car(string color, string typeOfCar)
        {
            this.color = color;
            this.typeOfCar = typeOfCar;
        }

        public static void setNbrOfWheels (int wheels)
        {
            nbrOfWheels = wheels;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car("Red", "SUV-AWD");
            Car car2 = new Car("Red", "CAR");

            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            Car.setNbrOfWheels(6);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            Car.setNbrOfWheels(8);
            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.ReadLine();            
        }
    }
}

Restrictions: 
  • Static methods cannot access non-static variables. If at all this is done, it will lead to compile time error.
  • "this" operator cannot be used in static methods. 
  • In order to set non-static variables, an instance needs to be created within the static methods. However, this would not make any sense as the object scope would be only in the static method.
The Why Section : If one really needs to understand any topic its very important to understand the whys? I do not like taking things on face value. Its good to know the facts, but its very important to understand the reasoning behind each fact. Lets go through the below questions to re-inforce the concepts.


1. Why cannot static methods access non-static variables (except by creating an instance within static method)?
A static method is associated with the class, so it cannot access any non-static variables. It would not know which instance's non-static variables to use.


2. Why this operator cannot be used in static method?
"this" implies an object/instance that is the reason this operator cannot be used in static method.



Static Data/Field

The concept is very simple that I have tried to explain with the screen-shot below.

Assumption : All cars whatsoever, will have same number of wheels.

                           In-memory allocation would like as below



  • In above picture - nbrOfWheels is defined static so that is being shared by all the objects/instances of the Class "Car". That means if nbrOfWheels is changed, all objects will see the change.
  • All Car instances (Car1, Car2), get their own copies of non-static fields. Meaning, Car1 will have its own color and carType and Car2 will have its own color and carType.

How this works internally?
     As the picture depicts, the CLR allocates the memory to the object only once. After that all the objects refer to the same memory location.

Lets look at the code below...

using System;

namespace StaticDataExample
{

    class Car
    {
        public static int nbrOfWheels = 4;
        public string color, typeOfCar;

        public Car(string color, string typeOfCar)
        {
            this.color = color;
            this.typeOfCar = typeOfCar;
        }

        public void setNbrOfWheels (int wheels)
        {
            nbrOfWheels = wheels;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car("Red", "SUV-AWD");
            Car car2 = new Car("Red", "CAR");

            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            car1.setNbrOfWheels(6);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            car2.setNbrOfWheels(8);
            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.ReadLine();            
        }
    }
}
output
  • The code above, shows how the static field is shared by all the instances.
  • Once the static field is changed by one object, the shared copy is changed too.
  • Static field is accessed by <Classname>.<staticVariableName>, in above example, refer to the highlighted portion of the code. Instance cannot at all access the static fields.

Sunday, April 20, 2014

Static Keyword

  • Static modifier belongs to the type itself rather than specific object. This means a static member belongs to the class rather than the instance of the class. For example Console.WriteLine. There is no need to create an instance of Console to invoke WriteLine. And if that is done, the compiler complains.
  • When is this used? This is implemented in case of utility classes where there is no need to implement object level state.
  • Static modifier can be applied to -           
                        - Data/field
                        - Method
                        - Property
                        - Constructor
                        - Class

   Click on each link above for detailed working of each of them.



  • static keyword has a major role in Singleton Design Pattern. For better understanding of this pattern, one has to understand the working of this modifier thoroughly.