How can we use default implementation of different interfaces? - c#

As I know, I need to upcast an instance of an inherited class to the interface where a needed method is implemented and then call it.
interface IProcess
{
void Do() { Console.WriteLine("doing"); }
//...
}
interface IWait
{
void Wait() { Console.WriteLine("waiting"); }
//...
}
class Example : IProcess, IWait { }
static void Main(string[] args)
{
Example item = new Example();
(item as IProcess).Do();
(item as IWait).Wait();
}
What if there are few interfaces with default implementation of different methods that I need? Is there some pattern that can solve this or maybe I should always use as keyword to call a method of a certain interface?

Another option in addition to #DavGarcia's answer - introduce an interface combining the needed ones and upcast to it:
interface IExample : IProcess, IWait { }
class Example : IExample { }
IExample item = new Example();
item.Do();
item.Wait();

If you are only calling the method once, I would do it like below. As ugly as it is, it is correct.
((IProcess)item).Do();
There are some other options that may be cleaner if you need to call more than once. You can convert to the interface:
IProcess itemProcess = item;
itemProcess.Do(); // Now call many times.
Usually though, I think you would be passing the object into a function that expects the interface:
void DoSomething(IProcess itemProcess) {
itemProcess.Do();
}
DoSomething(item);

You can override the methods in the implementing class and pass through control to the default implementation.
interface IProcess
{
void Do() { Console.WriteLine("doing"); }
}
interface IWait
{
void Wait() { Console.WriteLine("waiting"); }
}
class Example : IProcess, IWait
{
public void Do() => ((IProcess)this).Do();
public void Wait() => ((IWait)this).Wait();
}
Now you can do this:
static void Main(string[] args)
{
Example item = new Example();
item.Do();
item.Wait();
}

Related

Why does this code not return the class instance from the interface? [duplicate]

This question already has answers here:
Can a C# class call an interface's default interface method from its own implementation?
(3 answers)
Closed 8 months ago.
When this code is run (I'm using .NET 6.0), it recurses infinitely, and never gets to DoSomething() in IInterface, instead of returning the Class instance from the interface.
It seems because of the return type of the method in the class being the same as in the interface, the compiler seems to think the interface's method is being reimplemented in the class, and the method calls itself.
If the method's return type is changed to the concrete class, it works without a problem. Why is it?
using System;
public class Program
{
public static void Main()
{
var obj = new Class();
var ret = obj.DoSomething();
Console.WriteLine("Finished");
}
}
interface IInterface {
IInterface DoSomething() {
return new Class();
}
}
class Class : IInterface {
// Infinite recursion
public IInterface DoSomething() => ((IInterface)this).DoSomething();
// Works
//public Class DoSomething() => (Class)((IInterface)this).DoSomething();
}
If you mark your interface method as sealed it will prevent recursion, but you won't be able to re-implement the method in another class
interface IInterface {
sealed IInterface DoSomething() {
return new Class();
}
}
class Class : IInterface {
public IInterface DoSomething() => ((IInterface)this).DoSomething();
}
Alternatively, you could make the class implementation private, and access it from another method. This will allow you to re-implement the interface in another class.
internal class Class : IInterface
{
private IInterface DoSomething() => ((IInterface)this).DoSomething();
public IInterface DoSomethingPublic() => DoSomething();
}
Unfortunately, there just isn't support for what you want to do currently. There was a section in the original Default Interface Methods proposal about the possibility of using base() to explicitly call an inherited interface, but that was cut.
I admit that I am not very familiar with default interface methods, but I suspect that the default behavior is to override the implementation, and by marking the interface as sealed you prevent this from happening.
If someone has a better explanation, please correct me!
Some reading material:
Default Interface Methods Proposal
A similar question with hacky workarounds
A. Base class
Classic base class implementation:
class BaseClass {
protected void DoSomething() {
Console.WriteLine("Hello from BaseClass!");
}
}
class Class : BaseClass {
public new void DoSomething() // new or virtual + override
{
Console.WriteLine("Hello from Class");
base.DoSomething();
}
}
B. Helper method
static class Helper {
public static void DoSomething() => Console.WriteLine("Do something!");
}
interface IInterface {
void DoSomething() => Helper.DoSomething();
}
class Class : IInterface {
public void DoSomething() { Console.WriteLine("Hello from Class"); Helper.DoSomething();}
}
C. Static interface method
I would say that this seems to be a case for a base class not an interface, but one way to 'reuse' the interface method is to make the interface method static.
For example:
var obj = new Class();
obj.DoSomething();
Console.WriteLine("Finished");
interface IInterface {
static void DoSomething() {
Console.WriteLine("Hello from IInterface!");
}
}
class Class : IInterface {
public void DoSomething() { Console.WriteLine("Hello from Class"); IInterface.DoSomething();}
}
This prints:
Hello from Class
Hello from IInterface!
Finished

How can I call a method inherited from an interface directly from a class?

using System;
interface ISample{
abstract void SampleMethod();
}
class SampleClass: ISample{
void ISample.SampleMethod(){
Console.WriteLine("SampleMethod was called.");
}
}
class Program{
public static void Main (string[] args){
SampleClass smpcls = new SampleClass();
smpcls.ISample.SampleMethod();
}
}
This code works seamlessly. But I must call "ISample" interface from "smpcls" which is the instance of "SampleClass". How can I call "SampleMethod" directly from a instance of "SampleClass"?
For example:
...
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod() //I would like to call it like this.
smpcls.ISample.SampleMethod() //Not like this
...
why don't use this
void Main()
{
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod();
}
public interface ISample
{
public void SampleMethod();
}
public class SampleClass : ISample
{
public void SampleMethod()
{
Console.WriteLine("SampleMethod was called.");
}
}
or if have c# 8+ maybe you mean this
SampleClass smpcls = new SampleClass();
smpcls.AsISampleMethod();
//or if you don't want to create an extra method
smpcls.AsISample.SampleMethod();
public interface ISample
{
void SampleMethod()
{
Console.WriteLine("SampleMethod was called.");
}
}
public class SampleClass : ISample
{
public ISample AsISample => (ISample)this;
public void AsISampleMethod()
{
AsISample.SampleMethod();
}
}
but the interface works almost the same as an abstract class
SampleClass explicitly implements ISample.SampleMethod, which is not what you want. Simply change it to
class SampleClass: ISample{
void SampleMethod(){
Console.WriteLine("SampleMethod was called.");
}
}
You must cast it as the interface to access a explicitly implemented interface method
ISample smpcls = new SampleClass();
smpcls.SampleMethod();
You have to know that when implementing an interface's members there are two ways:
implement interface
implement interface explicitely
In your example you have selected implement interface explicitely.
void ISample.SampleMethod()
If you use this option, then you are telling the class that the method void ISample.SampleMethod() belongs to the interface and NOT to the class.
Why and when can you use explicit option? Well, suppose you have another method in your class which is called exactly SampleMethod()
Now, if you implement ISample then you will have a clash with this method as ISample contains a method with the same name. So, to sovle this you use the explicit option on the interface method.
public class SampleClass : ISample
{
void ISample.SampleMethod()
{
Console.WriteLine("interface method");
}
public void SampleMethod()
{
Console.WriteLine("class method");
}
}
In your calling code, this is how you call each method:
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod();
((ISample)smpcls).SampleMethod();
As you can see: ((ISample)smpcls).SampleMethod();
this belongs to the interface as you have to cast it to it.
The output from both methods will be as follows:
//class method
//interface method
If you do not have clashing methods, then use the option "implement interface" which will declare the code without the interface name:
public class SampleClass : ISample
{
public void SampleMethod()
{
Console.WriteLine("now this method belongs to the class");
}
}

How to make a specific order for calling methods?

For example, I have a class with interface, which has few methods.
What is the best way to call methods always only in a specific order in the class?
public class SomeClass
{
void Start(ISomeInterface testClass)
{
testClass.Method1();
testClass.Method2();
testClass.Method3();
}
}
public interface ISomeInterface
{
void Method1();//should run 2nd
void Method2();// 1st
void Method3();// 3rd
}
Take a look at Template Method Design Pattern
The intent of Template Method Design Pattern is to define the skeleton of an algorithm in an operation, deferring some
steps to client subclasses. Template Method lets subclasses redefine
certain steps of an algorithm without changing the algorithm's
structure.
abstract class SomeClass : ISomeInterface
{
public abstract void Method1();
public abstract void Method2();
public abstract void Method3();
// The template method
public void Start()
{
testClass.Method1();
testClass.Method2();
testClass.Method3();
}
}
class ImplementationClass : SomeClass
{
public override void Method1()
{
...
}
public override void Method2()
{
...
}
public override void Method3()
{
...
}
}
// Usage
var implementationClass = new ImplementationClass();
implementationClass.Start();
It's normal to write code so that methods are expected to run in certain order. But in that case we wouldn't want to just expose all of the methods and expect the caller to just "know" to run them in a certain order. If something is required then we must somehow enforce it.
If the methods of an interface can be executed in any order but in one specific case we want to run them in a particular order, that's easy. We just do them in the order we want:
testClass.Method2();
testClass.Method1();
testClass.Method3();
If methods must always be executed in a particular order then it doesn't make sense to expose an interface that allows us to execute them in just any order. The interface should describe how we want the class to be used. In that case this would make more sense:
public interface IDoesSomething
{
void DoSomething();
}
public class DoesSomething : IDoesSomething
{
public void DoSomething()
{
DoAnotherThing();
DoOneThing();
SomethingElse();
}
private void DoOneThing(){}
private void DoAnotherThing(){}
private void SomethingElse(){}
}
Now the interface tells other classes how to interact with it, but the details of how that gets done, which includes a particular sequence of steps, is encapsulated (hidden) inside the implementation of that class.
We're still doing the same thing - breaking a process into steps - but choosing how much of it we expose outside the class. We're making it easier to use our class correctly by making it impossible to use it incorrectly.
As far as I see, Template methodis not what you are looking for. (Unless you are one of those unpleasant people using answers without accepting ones ;))
If you'd like to give an illusion of freedom to a user and to punish one for using it wrong way, it could be done the following way.
Define an attribute:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class OrderAttribute : Attribute
{
public int Order { get; }
public OrderAttribute(int order) => Order = order;
}
Then define an interface:
public interface IObeyOrder
{
[Order(2)]
[Order(4)]
void Method1(); // should run 2nd or 4th
[Order(1)]
void Method2(); // 1st
[Order(3)]
void Method3(); // 3rd
void Method4(); // order doesn't matter
}
And implement it on a class, calling CheckOrder() first in each method:
public partial class ObeyOrder : IObeyOrder
{
public void Method1()
{
CheckOrder();
Console.WriteLine("Method1");
}
public void Method2()
{
CheckOrder();
Console.WriteLine("Method2");
}
public void Method3()
{
CheckOrder();
Console.WriteLine("Method3");
}
public void Method4()
{
CheckOrder();
Console.WriteLine("Method4");
}
public void Method5() // non-interface
{
CheckOrder();
Console.WriteLine("Method5");
}
}
where CheckOrder() is:
public partial class ObeyOrder : IObeyOrder
{
private static readonly Dictionary<string, int[]> orderedMethods = OrderHelper<IObeyOrder>.OrderedMethods;
private readonly Queue<int> orders = new Queue<int>(orderedMethods.Values.SelectMany(i => i).OrderBy(i => i));
private void CheckOrder([CallerMemberName] string methodName = "")
{
if (!orderedMethods.TryGetValue(methodName, out var methodOrders))
return;
var order = orders.Peek();
if (!methodOrders.Contains(order))
throw new Exception($"Wrong method call order. Method '{methodName}' with orders [{string.Join(", ", methodOrders)}]. Expected order {order}.");
orders.Enqueue(orders.Dequeue());
}
}
Of course, you can do it in a non-partial class.
public static class OrderHelper<T>
{
public static Dictionary<string, int[]> OrderedMethods { get; } = typeof(T)
.GetMethods()
.Select(method => new
{
Method = method.Name,
Orders = method.GetCustomAttributes(typeof(OrderAttribute), false)
.Cast<OrderAttribute>()
.Select(attribute => attribute.Order)
.ToArray()
})
.Where(method => method.Orders.Length > 0)
.ToDictionary(method => method.Method, method => method.Orders);
}
Usage:
var obeyOrder = new ObeyOrder();
obeyOrder.Method2(); // should go 1st
obeyOrder.Method4(); // can go whenever, since there is no order attribute
obeyOrder.Method1(); // should go 2nd or 4th
obeyOrder.Method5(); // can go whenever, since it's non-interface
obeyOrder.Method3(); // should go 3rd
obeyOrder.Method1(); // should go 2nd or 4th
obeyOrder.Method2(); // should go 1st (after the last had been already called)
works fine, but
var obeyOrder = new ObeyOrder();
obeyOrder.Method2(); // should go 1st
obeyOrder.Method4(); // can go whenever, since there is no order attribute
obeyOrder.Method1(); // should go 2nd or 4th
obeyOrder.Method5(); // can go whenever, since it's non-interface
obeyOrder.Method3(); // should go 3rd
obeyOrder.Method1(); // should go 2nd or 4th
obeyOrder.Method2(); // should go 1st (after the last had been already called)
obeyOrder.Method2(); // should throw since the 2nd (obeyOrder.Method1()) is expected
throws
Wrong method call order. Method 'Method2' with orders [1]. Expected order 2.
First of all i think you got some concepts mixed up, a class implements an interface, you cannot have an interface class. What you do by implementing an interface is ensure that the consumer class of the interface has to implement that method signature in his code.
Secondly, there is no way to execute methods in a certain order if they re in an interface, this is because interface methods (not the code itself from each method, an interface does NOT HAVE ANY LOGIC on it). Probably what you are looking for here is class (can be abstract not sure why do you need an interface though), and you could have this 3 methods as private members of it and have a public method that executes the 3 of them. Like this:
public class Example
{
private void MethodA()
{
//logic from methodA
}
private void MethodB()
{
//logic from methodB
}
private void MethodC()
{
//logic from methodC
}
public void MethodA()
{
MethodB();
MethodA();
MethodC();
}
}
Only expose the callable methods in an interface, and return a new interface when the method has been called.
interface IMethod1 {
IMethod2 Method1();
}
interface IMethod2 {
IMethod3 Method2();
}
Initially, you return a IMethod1. This only exposes Method1(), so it's not possible to call Method2 out of order. When calling Method1(), it returns an IMethod2 that exposes Method2(), so that can be called.
These interfaces can be implemented by the same class, which exposes only some methods at a time through the various interfaces.
Edit: I wrote a blog post about this: Enforcing object lifecycles through interfaces

Is there a way to hide the methods partially in child classes?

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.

Problem in Interfaces (polymorphism) C#

i have two classes which have some common methods like
funcA(), funcB()
and some methods are only related to its class...
what i did is made interface of TestInterface
public interface TestInterface
{
void funcA()
void funcB()
}
public class ClassA : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassA FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassA FuncB()");
}
public void myFuncA()
{
Console.WriteLine("This is My Own Function A");
}
}
public class ClassB : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassB FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassB FuncB()");
}
public void myFuncB()
{
Console.WriteLine("This is My Own Function B");
}
}
public static void main()
{
TestInterface test = new ClassA();
test.funcA();
}
as u see in above two classes. i have two functions myFuncA() and myFuncB() are not part of interface. they only belongs to their own class.
how can i call them from the main method. where i am creating object of TestInterface and initializing it with some child class.???
actually i have separate classes in DAL.
they have some common methods. and some methods related to their own class.
i want to implement Factory Pattern on this.
what should i do now?
If you're asking whether you can do something like:
public static void Main(string[] a)
{
TestInterface test = new ClassA();
test.myFuncA();
}
the answer is no. You would have to cast it to ClassA first. The fact that you think you need to do this indicates there is probably something wrong with your design.
TestInterface test = new ClassA();
test.myFuncA();
(test as ClassB).myFuncB();
Hopefully this was what you were looking for.
Make a new interface for ClassA and ClassB and you just need to cast the class to the correct interface to see the new functions.
public class ClassA : TestInterface, TestInterfaceA {
}
So, when you get the concrete instance just cast that to TestInterfaceA to see the functions specific to this class.
You can cast the TestInterface object, but it defeats the purpose of polymorphism...
public static void main()
{
TestInterface test = new ClassA();
test.funcA();
((ClassA) test).myFuncA();
}
Try casting. I assume from the question you meant something like this:
public void simpleMethod(TestInterface variableName) {
if (variableName is ClassA) {
((ClassA)variableName).myFuncA();
}
}
Mohsen I'm really confused with your question
if you just want to call MyFuncA() or MyFuncB() just you should create an instance of their own calss like
ClassA a = new ClassA();
a.FuncA(); //interface member
a.FuncB(); // interface member
a.MyFuncA(); //class A Member
I can't undrestand why you are trying to create an instance of your Interface and then call subclass methods!!!!
Am I right ? or Imisunderstood your issue ?
is it good to add methods of ClassA and ClassB into interface and provide null implementation in other class?
like
public interface TestInterface
{
void funcA();
void funcB();
void myFuncA();
void myFuncB();
}
public class ClassA:TestInterface
{
public void funcA()
{
// some code here
}
public void funcB()
{
// some code here
}
public void myFuncA()
{
// my own code here
}
public void funcB()
{
// null implementation
}
}
and vise versa of this in ClassB

Categories