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
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();
}
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:
All are valid, none really answer the question fully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With