If I have
public class AImplementation:IAInterface
{
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
((IAInterface)this).AInterfaceMethod();
}
}
How to call AInterfaceMethod() from AnotherMethod() without explicit casting?
There are lots of ways of doing this without using the cast operator.
Technique #1: Use "as" operator instead of cast operator.
void AnotherMethod()
{
(this as IAInterface).AInterfaceMethod(); // no cast here
}
Technique #2: use an implicit conversion via a local variable.
void AnotherMethod()
{
IAInterface ia = this;
ia.AInterfaceMethod(); // no cast here either
}
Technique #3: write an extension method:
static class Extensions
{
public static void DoIt(this IAInterface ia)
{
ia.AInterfaceMethod(); // no cast here!
}
}
...
void AnotherMethod()
{
this.DoIt(); // no cast here either!
}
Technique #4: Introduce a helper:
private IAInterface AsIA => this;
void AnotherMethod()
{
this.AsIA.IAInterfaceMethod(); // no casts here!
}
You can introduce a helper private property:
private IAInterface IAInterface => this;
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
Tried this and it works...
public class AImplementation : IAInterface
{
IAInterface IAInterface;
public AImplementation() {
IAInterface = (IAInterface)this;
}
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
}
And yet another way (which is a spin off of Eric's Technique #2 and also should give a compile time error if the interface is not implemented)
IAInterface AsIAInterface
{
get { return this; }
}
You can't, but if you have to do it a lot you could define a convenience helper:
private IAInterface that { get { return (IAInterface)this; } }
Whenever you want to call an interface method that was implemented explicitly you can use that.method() instead of ((IAInterface)this).method().
Yet another way (not best):
(this ?? default(IAInterface)).AInterfaceMethod();
Can't you just remove the "IAInterface." from the method signature?
public class AImplementation : IAInterface
{
public void AInterfaceMethod()
{
}
void AnotherMethod()
{
this.AInterfaceMethod();
}
}
Related
Please consider the attached figure.
What I want is that the (technical-) "User" can use methods from class A, B or C by an instantiate of "HeadClass". What I try to avoid is, that I have to add a separate function for each method defined in Class A, B and C to call them through the "HeadClass". I tried to describe this in an other stackoverflow-request yesterday but have deleted it because it seemed to be unclear what I wanted to achieve. So here is an other approach.
Usually this would be achieved by inheritance (if only one class would be inherited from). But, as they told me in that deleted post, I should use Interface instead. Now, so far I thought that I know how interface work (using almost for every class), but I can't figure how I achieve this describe problem.
How would I have to fill the "???" in "HeadClass"?
I am happy for any input. Thx in adavnce!
class User
{
public User(IHeadClass headObj)
{
_headObj = headObj
}
public DoStuff()
{
_headObj.Method_1
_headObj.Method_2
_headObj.HeadMethod
}
}
public class HeadClass : IHeadClass, ???
{
???
public HeadClass( ??? )
{
???
}
void HeadMethod()
{
... do head stuff
}
}
public class Class_A : IClass_A
{
public void Method_1 () { }
}
public class Class_B : IClass_B
{
public void Method_2 () { }
public void Method_3 () { }
}
public class Class_C : IClass_C
{
public void Method_4 () { }
}
I have check out this describing how to use interfaces instead. But this doesn't solve the above problem.
If I understand correctly you can use composition here. Something like this:
public interface IClass_A
{
void Method_1 ();
}
public interface IClass_B
{
void Method_2 ();
void Method_3 ();
}
public interface IClass_C
{
void Method_4 ();
}
public interface IHeadClass : IClass_A, IClass_B, IClass_C
{
void HeadMethod();
}
public class HeadClass : IHeadClass
{
private readonly IClass_A _a;
private readonly IClass_B _b;
private readonly IClass_C _c;
public HeadClass(IClass_A a, IClass_B b, IClass_C c)
{
_a = a;
_b = b;
_c = c;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1() => _a.Method_1();
public void Method_2() => _b.Method_2();
public void Method_3() => _b.Method_3();
public void Method_4() => _c.Method_4();
}
C# (unlike for example C++ or PHP) does not support multiple inheritance. Interfaces allows multiple inheritance, but they don't provide definitions of methods, only declarations.
I think solution could be pattern called fasade: write methods in HeadClass that calls methods in other classes. In this case interfaces are not necessary.
public class HeadClass
{
private Class_A _a;
private Class_B _b;
private Class_C _c;
public HeadClass( Class_A a, Class_B b, Class_C c )
{
_a=a;
_b=b;
_c=c;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1 () {
_a.Method_1();
}
public void Method_2 () {
_b.Method_2();
}
public void Method_3 () {
_b.Method_3();
}
public void Method_4 () {
_c.Method_4();
}
}
May I suggest instead that you have an interface passed instead of Class definition in your constructor?
public class HeadClass
{
private IMethod1 _method1;
private IMethod2 _method2;
private IMethod3 _method3;
private IMethod4 _method4;
public HeadClass( IMethod1 method1, IMethod2 method2, IMethod3 method3, IMethod4 method4)
{
_method1=method1;
_method2=method2;
_method3=method3;
_method4=method4;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1 () {
_method1.Method_1();
}
public void Method_2 () {
IMethod2.Method_2();
}
public void Method_3 () {
IMethod3.Method_3();
}
public void Method_4 () {
IMethod4.Method_4();
}
}
Now you have removed any direct coupling to a class, you are no only linked by interface.
Say you want to split method 2 and 3 into it's own two classes? this code, never has to change.
You can now reuse any class that has a definition of the interface, as a paramater. No code is defined twice, that does the same thing, in each input.
Because:
public class Method1 : IMethod1
{
}
public class Method2 : IMethod2
{
}
public class Method3 : IMethod3
{
}
public class Method4 : IMethod4
{
}
can now be parsed as parameters to HeadClass.
or, if you insist method 2 & 3 belong on the same class.
public class ClassA: IMethod1
{
}
public class ClassB: IMethod2, IMethod3
{
}
public class ClassC: IMethod4
{
}
Should be obvious from this example that the benefits lie in the fact that you can now do whatever you want in Headclass, and if you need behaviour to change, you can inject code via constructor, without having to retry the behaviour of headclass.
And headclass, doesn't know ClassA, B or C exist directly, only the interface.
I Believe this is called the Strategy pattern?
Picture a case like this:
I have a controller action (or service method) where I need to call three methods in a consecutive order, each method has a single responsibility.
public return_type MyMethod(_params_) {
// .. some code
Method_1 (...);
Method_2 (...);
Method_3 (...);
// ... some more code
}
A developer can make the mistake of calling Method_2 before Method_1, or at least we can say that nothing forces him to follow this order, or to get an exception when the order isn't followed.
Now we can call Method_2 inside Method_1, and Method_3 inside Method_2, but that doesn't seem right when each method handles a completely different responsibility.
Is there a design pattern for this situation? Or any "clean" way to handle this?
This is exactly what facade pattern do.
Try to extract the three methods to another class, and make them private. Expose a single method MyMethod that calls the other methods in the desired order. Clients should use Facade.MyMethod
More details: https://en.m.wikipedia.org/wiki/Facade_pattern
I suppose you should leave control of execution for yourself and give possibility just to set what should be executed.
public interface IMethodsExecutor
{
void Execute();
void ShouldRunMethod1();
void ShouldRunMethod2();
void ShouldRunMethod3();
}
public class MethodsExecutor: IMethodsExecutor
{
private bool _runMethod1;
private bool _runMethod2;
private bool _runMethod3;
public MethodsExecutor()
{
_runMethod1 = false;
_runMethod2 = false;
_runMethod3 = false;
}
public void ShouldRunMethod1()
{
_runMethod1 = true;
}
public void ShouldRunMethod2()
{
_runMethod2 = true;
}
public void ShouldRunMethod3()
{
_runMethod3 = true;
}
private void Method1()
{
}
private void Method2()
{
}
private void Method3()
{
}
public void Execute()
{
if (_runMethod1)
{
Method1();
}
if (_runMethod2)
{
Method2();
}
if (_runMethod3)
{
Method3();
}
}
}
So that the usage will be:
IMethodsExecutor methodsExecutor = new MethodsExecutor();
methodsExecutor.ShouldRunMethod1();
methodsExecutor.ShouldRunMethod3();
methodsExecutor.Execute();
We have a base class A which consists of 6 public methods :
public class A
{
public void method1()
{
// Implementation
}
public void method2()
{
// Implementation
}
.
.
.
.
public void method6()
{
// Implementation
}
}
We have two child class B and C which inherits from A. How can I implement it in such a way that Class B has access to only method1(),method2(),method3() and Class C has access to method4(),method5(),method6()??
You can't prevent something from using public class A methods, but you can definitely hide them with the proper use of interfaces.
interface IAOne
{
void method1();
void method2();
void method3();
}
interface IATwo
{
void method4();
void method5();
void method6();
}
class A : IAOne, IATwo
{
void method1() { }
void method2() { }
void method3() { }
void method4() { }
void method5() { }
void method6() { }
}
So now you have class B which never needs to know about A or about A's methods. It only knows about the IAOne interface. B can now also re-expose any methods (and even re-implement the interface) and delegate the implementation of those to A.
class B : IAOne
{
private IAOne _a;
public B(IAOne a) { _a = a; }
void method1() { _a.method1(); }
void method2() { _a.method2(); }
void method3() { _a.method3(); }
}
You basically can't do that. The fact that you're attempting to do it should serve as a warning that there is something wrong with your code.
I don't now why you have emphasize to use one class (A) with all 6 methods, but if you wanna get that may you should aspect programming design and put and interceptor on the head of your methods. Then you can check caller with MethodCallerInfo and control to each your child classes just call their own methods
public class A
{
private void MethodA(){}
}
public class B
{
private void MethodB() { }
}
public class C
{
private void MethodC() { }
}
I want to make sure that MethodA can be called only from MethodB. Other method can never call MethodA.
Make MethodA protected and use inheritance like this:
public class A
{
protected void MethodA()
{
}
}
public class B : A
{
private void MethodB()
{
//MethodA is accessible just here
}
}
public class C
{
private void MethodC()
{
//MethodA is not accessible here
}
}
But if you don't want to use inheritance and want all the classes in the same assembly you could only nest class B within class A and keep MethodA private. Like this:
public class A
{
private void MethodA()
{
}
public class B
{
private void MethodB()
{
A a = new A();
a.MethodA();
}
}
}
public class C
{
private void MethodC()
{
//MethodA is not accessible here
}
}
public class D : A
{
private void MethodC()
{
//MethodA is not accessible here
}
}
I note that S.Akbari's answer, though good, does not exactly meet your requirement. You said that you wanted MethodA to be callable only within B, but in their answer, MethodA is callable within A.
The solution to the problem you actually posed is to invert the nesting:
class B
{
private class A
{
public void MethodA() { }
}
}
Now MethodA can only be called from within B.
But the question is bizarre. If you have a method that can only be called from B then why is it not a member of B?
Given:
interface I
{
}
class B: I
{
}
class C: I
{
}
class A
{
public void Method(B arg)
{
}
public void Method(C arg)
{
}
public void Method(I arg)
{
// THIS is the method I want to simplify.
if (I is B)
{
this.Method(arg as B);
}
else if (I is C)
{
this.Method(arg as C);
}
}
}
I know that there are better ways to design this type of interactions, but because of
details which would take too long to explain this is not possible.
Since this pattern will be duplicated MANY times, I would like to replace the
conditional logic with a generic implementation which I could use just one line.
I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.
Any help would be appreciated.
I would put the method inside the interface and then let polymorphism decide which method to call
interface I
{
void Method();
}
class B : I
{
public void Method() { /* previously A.Method(B) */}
}
class C : I
{
public void Method() { /* previously A.Method(C) */ }
}
class A
{
public void Method(I obj)
{
obj.Method();
}
}
Now when you need to add a new class, you only need to implement I.Method. You don't need to touch A.Method.
What you want is double dispatch, and visitor pattern in particular.
This is kinda ugly but it gets the job done:
public void Method(B arg)
{
if (arg == null) return;
...
}
public void Method(C arg)
{
if (arg == null) return;
...
}
public void Method(I arg)
{
this.Method(arg as B);
this.Method(arg as C);
}
I don't think I would do it this way, though. It actually hurts looking at that. I'm sorry I forced you all to look at this as well.
interface I
{
}
class B : I
{
}
class C : I
{
}
class A
{
public void Method(B arg)
{
Console.WriteLine("I'm in B");
}
public void Method(C arg)
{
Console.WriteLine("I'm in C");
}
public void Method(I arg)
{
Type type = arg.GetType();
MethodInfo method = typeof(A).GetMethod("Method", new Type[] { type });
method.Invoke(this, new I[] { arg });
}
}
It doesn't exist in a convenient form withing C# - see here for an idea based on F#'s pattern matching, that does exactly what you want. You can do some things with reflection to select the overload at runtime, but that will be very slow, and has severe issues if anything satisfies both overloads. If you had a return value you could use the conditional operator;
return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0);
Again - not pretty.
Easy. In Visual Basic I do this all the time using CallByName.
Sub MethodBase(value as Object)
CallByName(Me, "RealMethod", CallType.Method, value)
This will call the overload of RealMethod that most closely matches the runtime type of value.
I'm sure you can use CallByName from C# by importing Microsoft.VisualBasic.Interaction or by creating your own version using reflection.