If I have two interfaces:
interface IGrandparent
{
void DoSomething();
}
interface IParent : IGrandparent
{
void DoSomethingElse();
}
then there are two implementations:
//only includes last interface from the inheritance chain
public class Child1 : IParent
{
public void DoSomething()
{
throw new NotImplementedException();
}
public void DoSomethingElse()
{
throw new NotImplementedException();
}
}
// includes all the interfaces from the inheritance chain
public class Child2 : IGrandparent, IParent
{
public void DoSomething()
{
throw new NotImplementedException();
}
public void DoSomethingElse()
{
throw new NotImplementedException();
}
}
Are these two implementations identical? (except the class name)? Some people say there are something to do with "implicit and explicit implementation", would some one explain why? I have seen Child2 style more than the other one.
Implicit interface implementation takes place when there is no conflicting method names from diffirent interfaces, and it is the common case.
Excplicit, on the other hand, is when there are conflicting method names, and at this point you have to specify which interface implements in the method.
public interface IFoo
{
void Do(); // conflicting name 1
}
public interface IBar
{
void Do(); // conflicting name 2
}
public class FooBar : IFoo, IBar
{
void IFoo.Do() // explicit implementation 1
{
}
void IBar.Do() // explicit implementation 1
{
}
}
Notice that excplicitly implemented interface methods cannot be public.
Here you can read more about explicit interface implementation.
Talking about your specific example. You can safely use only IParent. Even if you would like to use excplicit interface implementation, you still can do it without specifically mentioning IGrandparent in class declaration.
interface IGrandparent
{
void DoSomething();
}
interface IParent : IGrandparent
{
void DoSomethingElse();
void DoSomething();
}
public class Child : IParent
{
void IGrandparent.DoSomething()
{
}
public void DoSomethingElse()
{
}
public void DoSomething()
{
}
}
EDIT: As Dennis pointed out, there are several other cases of explicit interface implementation usage, including interface re-implementation. I found very good reasoning for implicit vs explicit interface implementation usages in here (you may also want to check out the whole thread, it's fascinating).
They are identical.
This is not about explicit interface implementation, because one can implement interface explicitly using both Child1 and Child2 styles, e.g.:
public class Child2 : IGrandparent, IParent
{
void IGrandparent.DoSomething()
{
throw new NotImplementedException();
}
public void DoSomethingElse()
{
throw new NotImplementedException();
}
}
public class Child1 : IParent
{
void IGrandparent.DoSomething()
{
throw new NotImplementedException();
}
public void DoSomethingElse()
{
throw new NotImplementedException();
}
}
Note, that this shouldn't be confused with interface re-implementation within class hierarchy:
public class Child1 : IParent
{
public void DoSomething()
{
Console.WriteLine("Child1.DoSomething");
}
public void DoSomethingElse()
{
Console.WriteLine("Child1.DoSomethingElse");
}
}
public class Child2 : Child1, IGrandparent
{
// Child2 re-implements IGrandparent
// using explicit interface implementation
void IGrandparent.DoSomething()
{
Console.WriteLine("Child2.DoSomething");
}
}
I'd avoid Child2 style. It's just a visual trash. Moreover, if IGrandparent isn't your responsibility, then sometime you will get this:
interface IGrandparent : ICthulhu { ... }
Do you want to update your code this way:
public class Child2 : ICthulhu, IGrandparent, IParent { ... }
?
Related
Consider the following snippet. How do I correctly implement the public void GiveFood(IAnimal d) part? The compiler wants implementations of the 2 separate member interfaces (ISeaAnimal and ILandAnimal) but they are handled by the IAnimal method.
interface IAnimal { }
interface ILandAnimal : IAnimal { }
interface ISeaAnimal : IAnimal { }
interface ICaretaker<in T> where T : IAnimal
{
void GiveFood(T d);
}
interface ISeaAnimalCaretaker<in T> : ICaretaker<T> where T : ISeaAnimal
{
void RefreshWater();
}
class SuperCaretaker : ISeaAnimalCaretaker<ISeaAnimal>, ICaretaker<IAnimal>
{
public void RefreshWater()
{
// ...
}
public void GiveFood(IAnimal d)
{
// ...
}
// ---> The below methods are redundant since GiveFood(IAnimal) is implemented, but the compiler wants them still
//public void GiveFood(ISeaAnimal d)
//{
// throw new NotImplementedException();
//}
//public void GiveFood(ILandAnimal d)
//{
// throw new NotImplementedException();
//}
How about using an explicit interface implementation? Note that SuperCaretaker implements both ICaretaker<IAnimal> and ICaretaker<ISeaAnimal>:
class SuperCaretaker : ISeaAnimalCaretaker<ISeaAnimal>, ICaretaker<IAnimal>
{
public void RefreshWater()
{
// ...
}
public void GiveFood(IAnimal d)
{
// ...
}
void ICaretaker<ISeaAnimal>.GiveFood(ISeaAnimal d) => GiveFood(d);
}
This way the ISeaAnimal method is hidden, unless you access it using an expression of type ICaretaker<ISeaAnimal> or ISeaAnimalCaretaker<ISeaAnimal>. This also means that you can just call GiveFood(d); in the implementation without causing infinite recursion.
You don't need the GiveFood(ILandAnimal) method, since SuperCaretaker doesn't implement ICaretaker<ILandAnimal>, but if it does (I don't see why you need to though...), you can write another explicit interface implementation.
Remove the ISeaAnimalCaretaker implementation from SuperCaretaker class, so you can handle IAnimal instances.
Like this:
class SuperCaretaker : ICaretaker<IAnimal>
{
public void RefreshWater()
{
// ...
}
public void GiveFood(IAnimal d)
{
// ...
}
// You don't need the other method anymore
}
So this question is a clear case of one stone kills two birds (a design and code question) I have a base class which has a base interface
interface IBase
{
IBase Method1();
}
abstract class Base : IBase
{
IBase Method1()
{
//do work
return this;
}
}
Now the child class
interface IChild1 : IBase
{
IChild1 ChildMethod();
}
class Child1 : Base, IChild1
{
public IChild1 ChildMethod()
{
//do work
// this would work fine Method1(); ChildMethod2();
//but I want to chain methods
Method1().ChildMethod2();
return this;
}
void ChildMethod2()
{
//do work
}
}
The crux of the matter is I want the base class to return the child class instance. As you can tell from the code in the method ChildMethod(), the base class method Method1() returns the instance of IBase so chaining ChildMethod2() would not be possible. Yes I could live without having to chain the method, but lets assume that is my only option.
Here is my attempt at using generics
interface IBase<T> where T : IBase<T>
{
T Method1();
}
abstract class Base<T> : IBase<T> where T : Base<T>
{
public T Method1()
{
//do work
return (T)this;
}
}
interface IChild1 : IBase<IChild1>
{
IChild1 ChildMethod();
}
class Child1 : Base<Child1>, IChild1
{
public IChild1 ChildMethod()
{
//do work
Method1(); ChildMethod2();
return this;
}
void ChildMethod2()
{
//do work
}
}
To put things clearly what I am trying to achieve is that for each call I make to the base class (interface in this case) I want the calling class/interface returned.
Note: Using Autofac for dependency injection
I think you can do it while preserving both interfaces and base class like this:
interface IBase<TSelf> where TSelf : IBase<TSelf> {
TSelf Method1();
}
interface IChild1 : IBase<IChild1> {
IChild1 ChildMethod();
void ChildMethod2();
}
class Base<TSelf> : IBase<TSelf> where TSelf : IBase<TSelf> {
public TSelf Method1() {
//do work
// need to double-cast here or just do
return (TSelf) (IBase<TSelf>) this;
}
}
class Child1 : Base<IChild1>, IChild1 {
public IChild1 ChildMethod() {
//do work
Method1().ChildMethod2();
return this;
}
public void ChildMethod2() {
//do work
}
}
But as you noted in comments, this won't work with more members in inheritance tree. If you can remove interfaces, you can do it like this:
public abstract class Base<TSelf> where TSelf : Base<TSelf> {
public TSelf Method1() {
//do work
// need to double-cast here or just do
return (TSelf) this;
}
}
internal class Child1Impl<TSelf> : Base<TSelf> where TSelf : Child1Impl<TSelf> {
public TSelf ChildMethod() {
//do work
Method1().ChildMethod2();
return (TSelf) this;
}
public void ChildMethod2() {
//do work
}
}
// create subclass for ease of use, so that caller should not do Child1Impl<Child1> every time
class Child1 : Child1Impl<Child1> {
}
class SubChild1Impl<TSelf> : Child1Impl<TSelf> where TSelf : SubChild1Impl<TSelf> {
public TSelf SubChildMethod() {
Method1().ChildMethod();
return (TSelf) this;
}
}
class SubChild1 : SubChild1Impl<SubChild1> {
}
Then you can do:
var test = new SubChild1();
test.Method1().ChildMethod().SubChildMethod();
Maybe you can somehow do the same with interfaces, but code is already quite complicated, will be even more complicated with interfaces (and you already have base class, so maybe you don't really need those interfaces).
i need to do something like this in c#. But in the Exec(object) i got a compilation error.
public class ParentClass { }
public class class1 : ParentClass
{
}
public class class2 : ParentClass
{
}
public class class3 : ParentClass
{
}
public class MasterClass
{
public void ExecutionMethod(ParentClass myObject)
{
//some code
Exec(myObject);
//some code
}
public void Exec(class1 obj)
{
//some code
}
public void Exec(class2 obj)
{
//some code
}
public void Exec(class3 obj)
{
//some code
}
}
I solved using Reflection but i think must be a better approach, somebody could give me a nice idea
As #ScottChamberlain pointed out in the comments, you don't have any methods that take an argument of type ParentClass.
Take a look at the Liskov substitution principle - if you've done your implementation properly, you can substitute an instance of, for example, class1 for an instance of ParentClass, but the converse is not true at all.
Odds are, you don't need (or want) the overloads anyway. Just have ParentClass be an abstract class with an abstract Execute method that all child classes have to implement, then you can just call Execute on the class directly without bothering with the overloads. Even better, just make ParentClass an interface. (This is sometimes called the Strategy Pattern by the way).
public interface IParent {
void Execute();
}
public class class1 : ParentClass {
//Execute method implementation
}
public class class2 : ParentClass {
// ...
}
public class class3 : ParentClass {
// ....
}
public class MasterClass
{
public void ExecutionMethod(IParent myObject)
{
//some code
myObject.Execute();
//some code
}
}
I suggest you have a look at object-oriented design patterns. Specifically, the strategy pattern for this problem. Anyway, you can implement what you want like this:
public interface IParent
{
void Exec();
}
public class Child1 : IParent
{
void Exec() { /*code*/ }
}
public class Child2 : IParent
{
void Exec() { /*code*/ }
}
public class Child3 : IParent
{
void Exec() { /*code*/ }
}
public class MasterClass
{
public void ExecutionMethod(IParent myObject)
{
//some code
myObject.Exec();
//some code
}
}
You could also use an abstract class instead of an interface, if you wanted the parent class to have some functionality for the Exec method - then the child classes would have to override the method.
You can use command pattern, with dependency injection. I kind of give you an idea below. The concrete implementation will call execute on your receiver ( you logic goes there
public interface ICommand
{
void Execute();
}
public class Command1 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class Command2 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class Command3 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class CommandManager
{
//you should use DI here to inject each concerete implementation of the command
private Dictionary<string, ICommand> _commands;
public CommandManager()
{
_commands = new Dictionary<string, ICommand>();
}
public void Execute(string key)
{
_commands[key].Execute();
}
}
The error your seeing is a result of your class1,2,3 objects being cast as their parent type because of the signature of the ExecutionMethod(xxx).
And not having an overridden method of Exec that takes a type of 'ParentClass' as the argument.
Probably the simplest method is to create an interface:
IDomainObject{}.
public class ParentClass : IDomainObject { }
public void ExecutionMethod(IDomainObject myObject)
{
Exec(myObject);
}
Using the interface in this way will prevent the downcast during the method call.
You need to use an interface here
Try changing ParentClass like this:
public interface IParentClass{}
Then make each of your classes implement it, like this:
public class class1 : IParentClass
{
}
public class class2 : IParentClass
{
}
Then in your MasterClass, try this:
public void ExecutionMethod(IParentClass myObject)
{
//some code
Exec(myObject);
//some code
}
public void Exec(IParentClass obj)
{
//some code
}
And then you can pass in any of your classes that implement the IParentClassinterface.
Now as an enhancement - if you want every implementation of IParentClass to have some methods and properties that you can invoke in your Exec method, do it like so:
public interface IParentClass
{
void DoTheThing();
}
This will force you to have this method in derived classes, so for example, class1 would look like this:
public class class1 : IParentClass
{
public void DoTheThing()
{
// things get done...
}
}
public class class2 : IParentClass
{
public void DoTheThing()
{
// things get done a different way...
}
}
And now in your Exec method, you can invoke like so:
public void Exec(IParentClass obj)
{
obj.DoTheThing();
}
In example below I want to create multiple types of Puppies inherited from PuppyBase base class that implements IPuppy generic interface. Bark method impemented in base class, the others - in derived CutePuppy class.
I can't get how can I create another puppy here who wants another feed and barks differently?
public interface IPuppy<TBark, TDesiredFood>
{
void Bark(TBark sound);
Task<TDesiredFood> Sleep();
Task Eat(TDesiredFood food);
}
public abstract class PuppyBase:IPuppy<Yap,Sausage>
{
public void Bark(Yap sound)
{
Console.WriteLine(sound.ToString());
}
public abstract Task<Sausage> Sleep();
public abstract Task Eat(Sausage food);
}
class CutePuppy : PuppyBase
{
public override Task<Sausage> Sleep()
{
// Implementation
// ...
throw new NotImplementedException();
}
public override Task Eat(Sausage food)
{
// Implementation
// ...
throw new NotImplementedException();
}
}
To be able to specify generic types on base class you may make it also generic
public abstract class PuppyBase<TBark, TDesiredFood> : IPuppy<TBark, TDesiredFood>
where TBark : ISound
{
public void Bark(TBark sound)
{
Console.WriteLine(sound.ToString());
}
public abstract Task<TDesiredFood> Sleep();
public abstract Task Eat(TDesiredFood food);
}
public interface ISound
{
string ToString();
}
This way for CutePuppy you should
class CutePuppy : PuppyBase<Yap,Sausage>
for NotSoNicePuppy
class NotSoNicePuppy: PuppyBase<Wow,Human>
This question seems weird, but i came across this question in one of the interviews recently.
I ve been asked, is there a way in c# to hide the methods partially in a inherited child classes?. Assume the base class A, exposed 4 methods. Class B implements A and it will only have the access to first 2 methods and Class C implements A will only have the access to last 2 methods.
I know we can do this way
public interface IFirstOne
{
void method1();
void method2();
}
public interface ISecondOne
{
void method3();
void method4();
}
class baseClass : IFirstOne, ISecondOne
{
#region IFirstOne Members
public void method1()
{
throw new NotImplementedException();
}
public void method2()
{
throw new NotImplementedException();
}
#endregion
#region ISecondOne Members
public void method3()
{
throw new NotImplementedException();
}
public void method4()
{
throw new NotImplementedException();
}
#endregion
}
class firstChild<T> where T : IFirstOne, new()
{
public void DoTest()
{
T objt = new T();
objt.method1();
objt.method2();
}
}
class secondChild<T> where T : ISecondOne, new()
{
public void DoTest()
{
T objt = new T();
objt.method3();
objt.method4();
}
}
But what they wanted is different. They wanted to hide these classes on inheriting from baseclasses. something like this
class baseClass : IFirstOne, ISecondOne
{
#region IFirstOne Members
baseClass()
{
}
public void method1()
{
throw new NotImplementedException();
}
public void method2()
{
throw new NotImplementedException();
}
#endregion
#region ISecondOne Members
public void method3()
{
throw new NotImplementedException();
}
public void method4()
{
throw new NotImplementedException();
}
#endregion
}
class firstChild : baseClass.IFirstOne //I know this syntax is weird, but something similar in the functionality
{
public void DoTest()
{
method1();
method2();
}
}
class secondChild : baseClass.ISecondOne
{
public void DoTest()
{
method3();
method4();
}
}
is there a way in c# we can achieve something like this...
I did it by having 1 main base class and 2 sub bases.
// Start with Base class of all methods
public class MyBase
{
protected void Method1()
{
}
protected void Method2()
{
}
protected void Method3()
{
}
protected void Method4()
{
}
}
// Create a A base class only exposing the methods that are allowed to the A class
public class MyBaseA : MyBase
{
public new void Method1()
{
base.Method1();
}
public new void Method2()
{
base.Method2();
}
}
// Create a A base class only exposing the methods that are allowed to the B class
public class MyBaseB : MyBase
{
public new void Method3()
{
base.Method3();
}
public new void Method4()
{
base.Method4();
}
}
// Create classes A and B
public class A : MyBaseA {}
public class B : MyBaseB {}
public class MyClass
{
void Test()
{
A a = new A();
// No access to Method 3 or 4
a.Method1();
a.Method2();
B b = new B();
// No Access to 1 or 2
b.Method3();
b.Method4();
}
}
Although you can't do exactly what you want, you could use explicit interface implementation to help, in which the interface members are only exposed if it is explicitly cast to that interface...
Perhaps the interviewer may have been referring to method hiding?
This is where you declare a method with the same signature as on in your base class - but you do not use the override keyword (either because you don't or you can't - as when the method in the base class is non-virtual).
Method hiding, as opposed to overriding, allows you to define a completely different method - one that is only callable through a reference to the derived class. If called through a reference to the base class you will call the original method on the base class.
Don't use inheritance. It makes the public or protected facilities of the base class available directly in the derived class, so it simply isn't want you want.
Instead, make the derived class implement the relevant interface, and (if necessary) forward the methods on to a private instance of the underlying class. That is, use composition (or "aggregation") instead of inheritance to extend the original class.
class firstChild : IFirstOne
{
private baseClass _owned = new baseClass();
public void method1() { _owned.method1(); }
// etc.
}
By the way, class names should start with an upper case letter.
There is 2 solutions to hide methods inherited from a base class:
As mentioned by thecoop, you can explicitely implement the interface declaring the methods you want to hide.
Or you can simply create these methods in the base class (not inherited from any interface) and mark them as private.
Regards.
What about injecting base class as an IFirst?
interface IFirst {
void method1();
void method2();
}
interface ISecond {
void method3();
void method4();
}
abstract class Base : IFirst, ISecond {
public abstract void method1();
public abstract void method2();
public abstract void method3();
public abstract void method4();
}
class FirstChild : IFirst {
private readonly IFirst _first;
public FirstChild(IFirst first) {
_first = first;
}
public void method1() { _first.method1(); }
public void method2() { _first.method2(); }
}
Injection keeps you from violating the Interface Segregation Principle. Pure inheritance means that your FirstChild is depending on an interface that it doesn't use. If you want to retain only the IFirst functionality in Base, but ignore the rest of it, then you cannot purely inherit from Base.