0

I was searching for interfaces example and I found one. The example is given below...

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

namespace InterFaceDemo
{
    interface IOne
    {
        void ONE();//Pure Abstract Method Signature
    }
    interface ITwo
    {
        void TWO();
    }
    interface IThree:IOne
    {
        void THREE();
    }
    interface IFour
    {
        void FOUR();
    }
    interface IFive:IThree
    {
        void FIVE();
    }
    interface IEVEN:ITwo,IFour
    {

    }
    class ODDEVEN:IEVEN,IFive//Must Implement all the abstract method, in Derived class.
    {
        public void ONE()//Implementation of Abstract Method.
        {
            Console.WriteLine("This is ONE");
        }
        public void TWO()
        {
            Console.WriteLine("This is TWO");
        }
        public void THREE()
        {
            Console.WriteLine("This is THERE");
        }
        public void FOUR()
        {
            Console.WriteLine("This is FOUR");
        }
        public void FIVE()
        {
            Console.WriteLine("This is FIVE");
        }

    }
}

Program.cs

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

namespace InterFaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This is ODD");
            IFive obj1 = new ODDEVEN();
            obj1.ONE();
            obj1.THREE();
            obj1.FIVE();

            Console.WriteLine("\n\nThis is EVEN");
            IEVEN obj2 = new ODDEVEN();
            obj2.TWO();
            obj2.FOUR();

            Console.ReadLine();
        }
    }
}

From this example interfaces concept got cleared but one thing is confusing for me and that is this line...

IFive obj1 = new ODDEVEN();

How he is making an object..from my thoughts he should make and object in this way

ODDEVEN obj1 = new ODDEVEN();

As he is making object of "ODDEVEN" class..can anyone explain me this object creation in simple words as i am new to programmimg...Thanks in advance

Krekkon
  • 1,349
  • 14
  • 35
Mudasir Sharif
  • 733
  • 2
  • 15
  • 31

1 Answers1

1

It's a shortcut for:

ODDEVEN temp = new ODDEVEN();
IFive obj1 = temp;

And that works because ODDEVEN implements IFive and therefore it is assignable to that interface reference.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Thanks Henk for your response...You mean to say that we must assign object of class that is implementing interface to interface object...? – Mudasir Sharif Mar 15 '14 at 13:11
  • Not "we must", but certainly "we can". This code is artificial, imagine a `void Foo(IFive fiver){}`. You can call it with my `temp` as `Foo(temp)`. – H H Mar 15 '14 at 14:15