Hemant Kumar
Hemant Kumar

Reputation: 4611

How can we implement the two interfaces having same method names?

I have a question that how can we implement the interfaces having same methodnames like this

 interface ISample2
{
  string CurrentTime();
     string CurrentTime(string name);
}
 interface ISample1
{
     string CurrentTime();
}

I did like this .Is this right?

class TwoInterfacesHavingSameMethodName:ISample1,ISample2
{
    static void Main(string[] sai)
    {
        ISample1 obj1 = new TwoInterfacesHavingSameMethodName();
        Console.Write(obj1.CurrentTime());
        ISample2 obj2 = new TwoInterfacesHavingSameMethodName();
        Console.Write(obj2.CurrentTime("SAI"));
        Console.ReadKey();
    }

    #region ISample1 Members

    string ISample1.CurrentTime()
    {
        return "Interface1:" + DateTime.Now.ToString();
    }

    #endregion

    #region ISample2 Members

    string ISample2.CurrentTime()
    {
        return "Interface2:FirstMethod" + DateTime.Now.ToString();
    }

    string ISample2.CurrentTime(string name)
    {
        return "Interface2:SecondMethod" + DateTime.Now.ToString() + "" + name;
    }

    #endregion
}

Here what is the meaning of this line:

ISample1 obj1 = new TwoInterfacesHavingSameMethodName();

Are we creating object for Class or Interface.What is the basic use of writing the methods in Interface.

Upvotes: 2

Views: 6387

Answers (2)

Itay Karo
Itay Karo

Reputation: 18306

When you explicitly implement an interface the explicit implementation will be called only if you call it from a reference to that interface.

so if you will write:

  TwoInterfacesHavingSameMethodName obj1 = new TwoInterfacesHavingSameMethodName();
  obj1.CurrentTime();

you will get an error.

but

ISample1 obj1 = new TwoInterfacesHavingSameMethodName();
ISample2 obj2 = new TwoInterfacesHavingSameMethodName();
obj1.CurrentTime();
obj2.CurrentTime();

will work.

if you want to call this function also on TwoInterfacesHavingSameMethodName you have to implicitly implement the interface as well. for ex:

public string CurrentTime()
{
   return "Implicit";
}

Upvotes: 5

S14df
S14df

Reputation: 125

Yes, what you did is correct. To answer your second question, you always create an object of a class and of type the interface. The use of writing methods in interface is to enforce all the classes to implement that method.

Upvotes: 0

Related Questions