locked
Difference between two types of creating an object RRS feed

  • Question

  • User-1590429200 posted

    Can anyone explain what is the difference between the below 2 approach in creating the objects 

    1.  IFoo tmp = new Foo1

    2. Foo1 tmp = new Foo1

    where IFoo is my interface and Foo1 is my class inheriting IFoo

    interface IFoo
    {
       void DoFoo();
    }
    
    class Foo1: IFoo
    {
        public DoFoo()
        {
    
        }
    }
    Tuesday, January 20, 2015 5:03 AM

Answers

  • User-760709272 posted

    1 this creates the object and returns a reference to the interface the object implements

    2 this creates the object and returns a reference to the object itself

    Dealing with things at an interface level means you can deal with any class that inherits that interface, and can only deal with things on that interface.

    public interface IFoo
    {
        void DoFoo();
    }
    
    public class Foo : IFoo
    {
    
        public void DoFoo()
        {
            System.Diagnostics.Debug.WriteLine("Foo.DoFoo");
        }
    
        public void Extra()
        {
            System.Diagnostics.Debug.WriteLine("Foo.Extra");
        }
    }
    
    public class Bar : IFoo
    {
        public void DoFoo()
        {
            System.Diagnostics.Debug.WriteLine("Bar.DoFoo");
        }
    
        public void Extra()
        {
            System.Diagnostics.Debug.WriteLine("Bar.Extra");
        }
    }
    
            public void FunctionInterface(IFoo f)
            {
                f.DoFoo();
            }
    
            public void FunctionObject(Foo f)
            {
                f.DoFoo();
    }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                IFoo fooInterface = new Foo();
                Foo fooObject = new Foo();
    
                FunctionInterface(fooInterface); // works
                FunctionObject(fooObject); // works
                fooInterface.Extra(); // doesn't work
                fooObject.Extra(); // works
    
                IFoo barInterface = new Bar();
                Bar barObject = new Bar();
    
                FunctionInterface(barInterface); // works
                FunctionObject(barObject); // doesn't work
                barInterface.Extra(); // doesn't work
                barObject.Extra(); // works
    
    
            }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 20, 2015 5:23 AM