C
C#2y ago
Binto86

✅ ✅ Use function that has default implementation in interface from instance of class

I have interface similar to this:
interface IFoo
{
void DoThing1();
void DoThing2();

void DoMultipleThings(int thing1, int thing2)
{
for (int i = 0; i < thing1; i++)
{
this.DoThing1();
for (int j = 0; j < thing2; j++)
{
this.DoThing2();
}
}
}
}
interface IFoo
{
void DoThing1();
void DoThing2();

void DoMultipleThings(int thing1, int thing2)
{
for (int i = 0; i < thing1; i++)
{
this.DoThing1();
for (int j = 0; j < thing2; j++)
{
this.DoThing2();
}
}
}
}
now i have class like this:
class Bar : IFoo
{
void DoThing1() => //something
void DoThing2() => //something
}
class Bar : IFoo
{
void DoThing1() => //something
void DoThing2() => //something
}
and i want to use it like this:
Bar bar = new Bar();
bar.DoMultipleThings(5, 5);
Bar bar = new Bar();
bar.DoMultipleThings(5, 5);
is this possible? maybe some keyword on the interface or something (i know i can cast it, but i don't want to do that)
6 Replies
HowNiceOfYou
HowNiceOfYou2y ago
You would need to either move the implementation of DoMultipleThings to the Bar class, or create a base class that implements the method.
Binto86
Binto86OP2y ago
they can
HowNiceOfYou
HowNiceOfYou2y ago
Wait, am I dumb? Hold on.... You're correct, I apologise.
Binto86
Binto86OP2y ago
ah thanks, i will just go abstract class than
HowNiceOfYou
HowNiceOfYou2y ago
Your code should work?
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?