Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How not to implement a function of an interface in class?

Tags:

c#

oop

interface

An interviewer asked me the following question in interview, but I don't know what could be the answer of this question, please help!!!

What must be done if i don't want to implement a function in my class that is declared in an interface which is implemented by my class.

Edited: I am using .NET with C#. It will be great if anyone can provide a sample code example in C#.

Thanks

like image 421
djmzfKnm Avatar asked Nov 28 '22 08:11

djmzfKnm


2 Answers

Implement the function, but throw an exception in the implementation.

In .NET, you typically use one of the following (there are similar exception types in other languages).

  • NotImplementedException: There is not yet an implementation of the method.

  • NotSupportedException: There will not be an implementation of the method in this class, by design. This appears several times in virtual methods of a base class, where a derived class is expected to offer an implementation where applicable. It also appears in explicit interface implementation methods (← this is the specific thing the interviewer asked), such as the ReadOnlyCollection<T> implementation of ICollection<T>.Add, etc.

For example, in C#:

public void MyNotSupportedInterfaceMethod()
{
  throw new NotImplementedException();
}

UPDATE: as marcos points out, if your class is abstract, you can leave the implementation to the inheritor, but you still have to declare it:

public abstract class MyClass : ISomeInterface
{
   public abstract void MyNotImplementedInterfaceMethod();
}
like image 95
Philippe Leybaert Avatar answered Dec 06 '22 17:12

Philippe Leybaert


These questions are always difficult to answer because it is hard to know what the interviewer was getting at. This question doesn't have a direct answer as all classes that implement an interface MUST implement its methods. You may be overthinking it if you are looking for some code to answer it.

In my opinion this question only has value if asked verbally as there is no real answer, but you can learn how the interviewee thinks. Possible answers could be:

  • Implement the method but throw an exception.
  • Make the class abstract and declare the method as abstract.
  • Remove the method from the interface definition.
  • I don't think this is possible.

All are valid, none really answer the question fully.

like image 26
Jack Ryan Avatar answered Dec 06 '22 17:12

Jack Ryan