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.
Related
Don't get me wrong: I do not want to force an overriding method to call the base class like already asked 1000...times before :)
I wondered if there is any way to force the call of the base class implementation of a method inside the base class.
Example:
using System;
public class Program
{
public static void Main()
{
var c = new SubClass();
c.CallInfo();
}
internal class BaseClass {
protected virtual void Info(){
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo() {
this.Info();
}
}
internal class SubClass : BaseClass {
protected override void Info() {
Console.WriteLine("SubClass");
}
internal override void CallInfo() {
base.CallInfo();
}
}
}
Output obviously would be SubClass. Is there any way to force the CallInfo method of BaseClass to call its own Info method so that the output would be BaseClass?
By marking your Info() method as virtual you are specifically asking for this type of inheritance behaviour to occur.
If you want to ensure that a method call in your base class is not overridden, you'll need to use a non-virtual method, e.g.
internal class BaseClass {
protected virtual void Info(){
this.FinalInfo();
}
protected void FinalInfo() {
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo() {
this.FinalInfo();
}
}
No, you can't do that. The purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called it from base classes.
If that causes problems then the method you want to run should not be a virtual method.
This would work, while it won't force an implementation by a subclass like virtual it'll allow you to override it.
public class Program
{
public static void Main()
{
var c = new SubClass();
c.CallInfo();
}
internal class BaseClass
{
protected void Info()
{
Console.WriteLine("BaseClass");
}
internal virtual void CallInfo()
{
this.Info();
}
}
internal class SubClass : BaseClass
{
protected new void Info()
{
Console.WriteLine("SubClass");
}
internal override void CallInfo()
{
base.CallInfo();
}
}
}
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 { ... }
?
Say I have a base class like this:
public abstract class MyBaseClass
{
protected void MyMethod(string myVariable)
{
//...
}
}
Then I inherit this class in a separate assembly:
public abstract class MyDerivedClass : MyBaseClass
{
static readonly string MyConstantString = "Hello";
protected void MyMethod()
{
MyMethod(MyConstantString);
}
}
I now want to make sure that any other class that inherits from MyDerivedClass does not have access to the MyBaseClass.MyMethod() method. (To clarify, I still want to be able to call MyDerivedClass.MyMethod() with no parameters)
I tried using protected internal but that didn't work.
Update: I'm trying to do this because the application I'm working on has a bunch of separate programs that use a base class. There are 5 different "types" of programs, each performs a specific, separate function but they all have some common code that I am trying to abstract into this base class. The common code is 99% the same, differing only slightly depending on what type of program is calling it. This is why I have my base class taking a string parameter in the example which then disappears in the derived base class, as that class knows it performs role x so it tells its base class accordingly.
Then I would instead of inheritance use composition in the MyDerivedClass. So all derived classes from this class does not know the methods from MyBaseClass. The class MyBaseClass would i make package visible so it is not possible to use it.
abstract class MyBaseClass
{
void MyMethod(string myVariable)
{
//...
}
}
abstract class MyDerivedClass
{
static readonly string MyConstantString = "Hello";
private MyBaseClass baseClass;
MyDerivedClass(MyBaseClass baseClass)
{
this.baseClass = baseClass;
}
protected void MyMethod()
{
baseClass.MyMethod(MyConstantString);
}
}
The class names should be changed of course.
This is not quite possible. And it may be a sign that your object design might be in trouble, but that's not a question for SO.
You can try a bit more underhanded approach, though:
public abstract class MyBaseClass
{
protected abstract string MyConstantString { get; }
protected void MyMethod()
{
//...
}
}
public abstract class MyDerivedClass : MyBaseClass
{
protected override sealed string MyConstantString => "Hello";
}
Or, more typically, just use the constructor to pass the required argument:
public abstract class MyBaseClass
{
private readonly string myString;
protected MyBaseClass(string myString)
{
this.myString = myString;
}
protected void MyMethod()
{
//...
}
}
public abstract class MyDerivedClass : MyBaseClass
{
protected MyBaseClass() : base("Hello") {}
}
Classes derived from MyDerivedClass have no way to change the argument in either case, the second approach is a bit nicer from inheritance perspective (basically, the type is a closure over an argument of its ancestor type).
You cannot stop inheriting classes from calling this method - you have made it protected so your intent is for it to be accessible to classes that inherit from it, whether directly, or via another sub-class.
If you want to keep the inheritance, the best you can do is to throw an error if the sub-class calls it in MyDerivedClass:
public abstract class MyBaseClass
{
protected void MyMethod(string myVariable)
{
Console.WriteLine(myVariable);
}
}
public abstract class MyDerivedClass : MyBaseClass
{
static readonly string MyConstantString = "Hello";
protected void MyMethod()
{
base.MyMethod(MyConstantString);
}
protected new void MyMethod(string myVariable)
{
throw new Exception("Not allowed");
}
}
public class SubDerivedClass : MyDerivedClass
{
static readonly string MyConstantString = "Hello";
public void Foo()
{
MyMethod(MyConstantString);
}
}
When Foo() is called in SubDerivedClass, it will call MyMethod in DerivedClass, which will throw the Exception.
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>
I have this situation that when AbstractMethod method is invoked from ImplementClass I want to enforce that MustBeCalled method in the AbstractClass is invoked. I’ve never come across this situation before. Thank you!
public abstract class AbstractClass
{
public abstract void AbstractMethod();
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
}
public class ImplementClass : AbstractClass
{
public override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
An option would be to have the Abstract class do the calling in this manner. Otherwise, there is no way in c# to require an inherited class to implement a method in a certain way.
public abstract class AbstractClass
{
public void PerformThisFunction()
{
MustBeCalled();
AbstractMethod();
}
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
//could also be public if desired
protected abstract void AbstractMethod();
}
public class ImplementClass : AbstractClass
{
protected override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
Doing this creates the desired public facing method in the abstract class, giving the abstract class over how and in what order things are called, while still allowing the concrete class to provide needed functionality.
How about
public abstract class AbstractClass
{
public void AbstractMethod()
{
MustBeCalled();
InternalAbstractMethod();
}
protected abstract void InternalAbstractMethod();
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
}
public class ImplementClass : AbstractClass
{
protected override void InternalAbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
Why can't you just call the method in the AbstractMethod() of Implement class?
One thing the preceding solutions ignore is that ImplementClass can redefine MethodToBeCalled and not call MustBeCalled -
public abstract class AbstractClass
{
public abstract void AbstractMethod();
private void MustBeCalled()
{
//will be invoked by MethodToBeCalled();
Console.WriteLine("AbstractClass.MustBeCalled");
}
public void MethodToBeCalled()
{
MustBeCalled();
AbstractMethod();
}
}
public class ImplementClass : AbstractClass
{
public override void AbstractMethod()
{
Console.WriteLine("ImplementClass.InternalAbstractMethod");
}
public new void MethodToBeCalled() {
AbstractMethod();
}
}
If only C# allowed non-overridden methods to be sealed - like Java's final keyword!
The only way I can think of to overcome this is to use delegation rather than inheritance, because classes can be defined as sealed. And I'm using a namespace and the "internal" access modifier to prevent providing a new implementation on implementing classes. Also, the method to override must be defined as protected, otherwise users could call it directly.
namespace Something
{
public sealed class OuterClass
{
private AbstractInnerClass inner;
public OuterClass(AbstractInnerClass inner)
{
this.inner = inner;
}
public void MethodToBeCalled()
{
MustBeCalled();
inner.CalledByOuter();
}
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
System.Console.WriteLine("OuterClass.MustBeCalled");
}
}
public abstract class AbstractInnerClass
{
internal void CalledByOuter()
{
AbstractMethod();
}
protected abstract void AbstractMethod();
}
}
public class ImplementInnerClass : Something.AbstractInnerClass
{
protected override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
System.Console.WriteLine("ImplementInnerClass.AbstractMethod");
}
public new void CalledByOuter()
{
System.Console.WriteLine("doesn't work");
}
}