Inheritance same methods implementation - c#

I have the following code. (in c#)
interface 1:
public interface iBclass
{
int addition(int a);
int s(); //and more methods from this ......
}
interface 2:
public interface iAclass
{
int addition(int a);
//more methods.....
}
Class that inherits both interfaces:
public class dClass : iAclass , iBclass
{
int iAclass.addition(int a)
{
return 0;
}
int iBclass.addition(int a)
{
return 1;
}
public int s()
{
return 3;
}
}
the problem is i am not able to access the Method iAclass.addition(int a) and iBclass.addition(int a) with the d object.
dClass d = new dClass();
how can i access those method by 'd' object? and why those interface methods are not allow to define as public?

The interfaces are implemented explicitly. So you can only call them by using the interface:
dClass d = new dClass();
iAclass a = (iAclass)d;
a.addition(123); // Calls implementation for iAclass
iBclass b = (iBclass)d;
b.addition(123); // Calls implementation for iBclass
See this link for details.

Related

How to choose the right strategy at runtime when implementing the strategy pattern?

Problem description
Consider the following implementation of the strategy pattern:
// this is the strategy definition
public interface ICalculator
{
int ComputeResult(int a, int b);
}
// this is an implementation of the strategy
public sealed class SumCalculator: ICalculator
{
public int ComputeResult(int a, int b) => a + b;
}
// this is another implementation of the strategy
public sealed class SubtractionCalculator: ICalculator
{
public int ComputeResult(int a, int b) => a - b;
}
Let's suppose we need to write some client code for the ICalculator service. The client code is given the following input data:
an integer number, via the variable a
another integer number, via the variable b
contextual information used to decide which strategy needs to be used. Let's suppose to have an enum named TaskType whose possible values are Sum and Subtract.
From a functional perspective, the client code should do something like this:
int a = GetFirstOperand();
int b = GetSecondOperand();
TaskType taskType = GetTaskType();
ICalculator calculator = null;
switch(taskType)
{
case TaskType.Sum:
calculator = new SumCalculator();
break;
case TaskType.Subtract:
calculator = new SubtractionCalculator();
break;
default:
throw new NotSupportedException($"Task type {taskType} is not supported");
}
int result = calculator.ComputeResult(a,b);
Console.Writeline($"The result is: {result}");
Consider now a codebase using dependency injection and delegating object creation and lifetime management to a DI container. In this case, the client code of the ICalculator service can't directly take the responsibility of creating objects.
What I'm trying to find is, basically, an elegant and effective way to solve this problem.
What I usually do in this scenario
This is what I usually do to solve this problem. I call this design pattern the composite design pattern, but I'm quite sure this is not exactly the pattern named composite design pattern in the gang of four book.
First of all, a reshape of the ICalculator interface is needed (more on this later):
public interface ICalculator
{
int ComputeResult(int a, int b, TaskType taskType);
bool CanHandleTask(TaskType taskType);
}
The existing interface implementations need to be changed:
public sealed class SumCalculator: ICalculator
{
public int ComputeResult(int a, int b, TaskType taskType)
{
if (!this.CanHandleTask(taskType))
{
throw new InvalidOperationException($"{nameof(SumCalculator)} cannot handle task {taskType}");
}
return a + b;
}
public bool CanHandleTask(TaskType taskType) => taskType == TaskType.Sum;
}
public sealed class SubtractionCalculator: ICalculator
{
public int ComputeResult(int a, int b, TaskType taskType)
{
if (!this.CanHandleTask(taskType))
{
throw new InvalidOperationException($"{nameof(SubtractionCalculator)} cannot handle task {taskType}");
}
return a - b;
}
public bool CanHandleTask(TaskType taskType) => taskType == TaskType.Subtract;
}
A third implementation of the ICalculator interface needs to be written. I call this object the composite object:
public sealed class CompositeCalculator: ICalculator
{
private readonly IEnumerable<ICalculator> _calculators;
public CompositeCalculator(IEnumerable<ICalculator> calculators)
{
_calculators = calculators ?? throw new ArgumentNullException(nameof(calculators));
}
public int ComputeResult(int a, int b, TaskType taskType)
{
if (!this.CanHandleTask(taskType))
{
throw new InvalidOperationException($"{nameof(CompositeCalculator)} cannot handle task {taskType}");
}
var handler = _calculators.First(x => x.CanHandleTask(taskType));
return handler.ComputeResult(a, b, taskType);
}
public bool CanHandleTask(TaskType taskType) => _calculators.Any(x => x.CanHandleTask(taskType));
}
This is the client code of ICalculator:
// this class encapsulates the client code of ICalculator
public sealed class AnotherService
{
private readonly ICalculator _calculator;
public AnotherService(ICalculator calculator)
{
_calculator = calculator ?? throw new ArgumentNullException(nameof(calculator));
}
public void DoSomething()
{
// code omitted for brevity
int a = ...;
int b = ...;
TaskType taskType = ...;
var result = _calculator.ComputeResult(a, b, taskType);
Console.Writeline($"The result is {result}");
}
}
Finally, here is the registration of the ICalculator interface in the DI container:
services.AddSingleton<SumCalculator>();
services.AddSingleton<SubtractionCalculator>();
services.AddSingleton<ICalculator>(sp =>
{
var calculators = new List<ICalculator>
{
sp.GetRequiredService<SumCalculator>(),
sp.GetRequiredService<SubtractionCalculator>()
};
return new CompositeCalculator(calculators);
});
This pattern works, but I don't like the fact that the ICalculator interface needs to be modified in order to introduce the CanHandleTask method and the extraneous parameter taskType to the ComputeResult method.
The original definition of the ICalculator interface (see the Problem description above) seems to be a more natural definition for a service able to compute a result using two integer numbers as input to the computation.
An alternative solution
An alternative solution to this problem is introducing a factory object for the ICalculator interface. This is somewhat similar to the IHttpClientFactory interface introduced in .NET core.
This way we can keep the original definition for the ICalculator interface:
public interface ICalculator
{
int ComputeResult(int a, int b);
}
We need to introduce a factory object for ICalculator instances:
public interface ICalculatorFactory
{
ICalculator CreateCalculator(TaskType taskType);
}
These are the implementations of the ICalculator interface (no more need for the composite object):
public sealed class SumCalculator: ICalculator
{
public int ComputeResult(int a, int b) => a + b;
}
public sealed class SubtractionCalculator: ICalculator
{
public int ComputeResult(int a, int b) => a - b;
}
This is the new version of the client code:
// this class encapsulates the client code of ICalculator
public sealed class AnotherService
{
private readonly ICalculatorFactory _calculatorFactory;
public AnotherService(ICalculatorFactory calculatorFactory)
{
_calculatorFactory = calculatorFactory ?? throw new ArgumentNullException(nameof(calculatorFactory));
}
public void DoSomething()
{
// code omitted for brevity
int a = ...;
int b = ...;
TaskType taskType = ...;
var calculator = _calculatorFactory.CreateCalculator(taskType);
var result = calculator.ComputeResult(a, b);
Console.Writeline($"The result is {result}");
}
}
The concrete implementation for the ICalculatorFactory interface delegates the object creation to the DI container and is defined inside the composition root (because it depends on the DI container directly):
public sealed class ServiceProviderCalculatorFactory: ICalculatorFactory
{
private readonly IServiceProvider _serviceProvider;
public ServiceProviderCalculatorFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
public ICalculator CreateCalculator(TaskType taskType)
{
switch(taskType)
{
case TaskType.Sum:
return _serviceProvider.GetRequiredService<SumCalculator>();
case TaskType.Subtract:
return _serviceProvider.GetRequiredService<SubtractionCalculator>();
default:
throw new NotSupportedException($"Task type {taskType} is not supported");
}
}
}
Finally, here is the service registration on the DI container:
services.AddSingleton<SumCalculator>();
services.AddSingleton<SubtractionCalculator>();
services.AddSingleton<ICalculatorFactory, ServiceProviderCalculatorFactory>();
The main advantange of this solution is avoiding all of the CanHandle ceremony of the composite pattern described above.
Question
Is there a better or canonical way to resolve this problem ?
Consider now a codebase using dependency injection and delegating object creation and lifetime management to a DI container.
It is possible to inject dependencies through constructor. Let me show an example.
I've little bit changed names. So now enum will look like this:
public enum OperationType
{
Sum,
Subtract
}
This is your abstraction:
public interface IOperation
{
int Compute(int a, int b);
}
And its concrete implementations:
public class SumOperation : IOperation
{
public int Compute(int a, int b) => a + b;
}
public class SubtractionOperation : IOperation
{
public int Compute(int a, int b) => a - b;
}
And then we inject all dependencies through constructor to allow future clients of CalculatorOperationFactory to use concrete implementations of IOperation by operation type:
public class CalculatorOperationFactory
{
private Dictionary<OperationType, IOperation> _operationByType;
public CalculatorOperationFactory(SumOperation sumOperation,
SubtractionOperation subtractionOperation)
{
_operationByType = new Dictionary<OperationType, IOperation>()
{
{ OperationType.Sum, sumOperation },
{ OperationType.Subtract, subtractionOperation },
};
}
public IOperation GetInstanceByOperationType(OperationType taskType)
=> _operationByType[taskType];
}
And then you can inject CalculatorOperationFactory to AnotherService:
public class AnotherService
{
CalculatorOperationFactory _calculatorFactory;
public AnotherService(CalculatorOperationFactory calculatorFactory)
{
_calculatorFactory = calculatorFactory;
}
public void DoSomething()
{
// code is omitted for brevity
int a = 0;
int b = 1;
OperationType taskType = OperationType.Sum;
IOperation operation = _calculatorFactory
.GetInstanceByTaskType(taskType);
var result = operation.Compute(a, b);
}
}
And your dependencies will look like this:
services.AddSingleton<SumOperation>();
services.AddSingleton<SubtractionOperation>();
services.AddSingleton<CalculatorFactory>();
Maybe a slight variation of the first solution:
public interface ICalculatorStrategy
{
int ComputeResult(int a, int b);
TaskType TaskType { get; }
}
public class SumCalculator : ICalculatorStrategy
{
public int ComputeResult(int a, int b) => a + b;
public TaskType TaskType => TaskType.Sum;
}
public sealed class SubtractionCalculator: ICalculatorStrategy
{
public int ComputeResult(int a, int b) => a - b;
public TaskType TaskType => TaskType.Subtract;
}
public interface ICalculator
{
public int ComputeResult(int a, int b, TaskType type);
}
public class Calculator : ICalculator
{
private readonly IEnumerable<ICalculatorStrategy> _strategies;
public Calculator(IEnumerable<ICalculatorStrategy> strategies) =>
_strategies = strategies;
public int ComputeResult(int a, int b, TaskType type)
{
var strategy = _strategies.FirstOrDefault(s => s.TaskType == type)
?? throw new InvalidOperationException($"No strategy found for type {type}");
return strategy.ComputeResult(a, b);
}
}
MS DI container can inject the IEnumerable<ICalculatorStrategy> for you.
services.AddTransient<ICalculatorStrategy, SumCalculator>();
services.AddTransient<ICalculatorStrategy, SubtractionCalculator>();
services.AddTransient<ICalculator, Calculator>();
I would argue that second approach is quite qood. Another way you can handle it is by switching to container which supports keyed dependencies like Autofac and use it to generate a Func factory as in this snippet created some years ago:
var builder = new ContainerBuilder();
builder.RegisterType<ImplOne>()
.Keyed<IDependency>(MyTypeEnum.TypeOne)
.SingleInstance();
builder.RegisterType<ImplTwo>()
.Keyed<IDependency>(MyTypeEnum.TypeTwo)
.SingleInstance();
builder.Register((c, p) =>
{
var type = p.TypedAs<MyTypeEnum>();
var resolve = c.Resolve<IIndex<MyTypeEnum, IDependency>>();
return resolve[type];
});
var container = builder.Build();
Func<MyTypeEnum, IDependency> factory = container.Resolve<Func<MyTypeEnum, IDependency>>();
var dependency = factory(MyTypeEnum.TypeOne);

nested classes and interfaces

(I really struggled with coming up with a good title for this question, if anyone wants to help out with that..)
So I'm having an issue designing something. Essentially I have a class A, which is composed of an array of objects of type B. I only want the interface of class A to be exposed, and want to keep class B essentially hidden to any user. I want to be able to perform operations on type B and its data, but only through class A's interface/methods calling methods of an instance of B. The part where it gets tricky is that I want to create a method that performs operations on members of type B, but I wanted to implement an interface and then have a class that implements that interface because I want my user to be able to create their own implementation of this method. I was thinking of doing somtehing like:
public class A
{
B[] arr;
C c;
public A(C c)
{
arr = new B[100];
this.c = c;
}
public void method1()
{
var b = new B();
b.someMethodofb(c); // pass c to the method of b
}
private class B
{
someMethodOfb(C c)
{
}
}
}
public class C : Interface1
{
public void method(B b)
{
//interface method we have implemented
}
}
I made the class B private because I only want class A to be publicly available so anything that happens to class B happens through class A, which is also why I nested B within A. But since class B is private, will I be able to use it as a parameter for the method of my class C? The method of Interface1 implemented is going to affect the internal implementation of how B performs someMethodOfb, which is why I think I need to pass it in to be able to maintain the hidden nature of class B. Could there be a better way for me to design this and be able to achieve the goals I set out in the first paragraph?
I would suggest you add another interface for the public known side of B, have B implement that interface and have C's method(s) use the interface.
public interface IC {
void method(IB b);
}
public interface IB {
int Priority { get; set; }
int Urgency { get; set; }
}
public class A {
B[] arr;
IC c;
public A(C c) {
arr = new B[100];
this.c = c;
}
public void method1() {
var r = (new Random()).Next(100);
arr[r].someMethodOfB(c); // pass c to the method of b
}
private class B : IB {
public int Priority { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int Urgency { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
internal void someMethodOfB(IC aC) {
aC.method(this);
throw new NotImplementedException();
}
}
}
public class C : IC { // user implements
public void method(IB b) {
if (b.Priority > 10 || b.Urgency > 10)
; // do something with BI using b
throw new NotImplementedException();
}
}
Now the user of the classes needs to know IC so they can create C and they need to know IB so they can write the body of the methods in C, but they don't need to know all of B or have access to B.
Let's use concrete examples :)
Say, we have three classes: Customer, Order, and OrderProcessor. Customer and Order are entities representing a customer and an order respectively, while OrderProcessor will process an order:
public interface IOrderProcessor
{
void ProcessOrder(IOrder order);
}
public interface IOrder
{
void FinalizeSelf(IOrderProcessor oProc);
int CustomerId {get; set;}
}
public class Customer
{
List<IOrder> _orders;
IOrderProcessor _oProc;
int _id;
public Customer(IOrderProcessor oProc, int CustId)
{
_oProc = oProc;
_orders = new List<IOrder>();
_id = CustId;
}
public void CreateNewOrder()
{
IOrder _order = new Order() { CustomerId = _id };
_order.FinalizeSelf(_oProc);
_orders.Add(_order);
}
private class Order : IOrder
{
public int CustomerId {get; set;}
public void FinalizeSelf(IOrderProcessor oProcessor)
{
oProcessor.ProcessOrder(this);
}
}
}
public class ConcreteProcessor : IOrderProcessor
{
public void ProcessOrder(IOrder order)
{
//Do something
}
}

Member pass-through in C#?

Go has a nice feature where members of a nested struct are automatically accessible via its parent struct:
// Server exposes all the methods that Logger has
type Server struct {
Host string
Port int
*log.Logger
}
// initialize the embedded type the usual way
server := &Server{"localhost", 80, log.New(...)}
// methods implemented on the embedded struct are passed through
server.Log(...) // calls server.Logger.Log(...)
// the field name of the embedded type is its type name (in this case Logger)
var logger *log.Logger = server.Logger
Is the same possible in C#, for example using implicit casts?
struct B
{
public int x;
}
struct A
{
public B b;
}
var a = new A();
a.b.x = 1; // How it usually works
a.x = 1; // How Go works, assuming x is unambiguous
There is no such concept in C#. You can add such properties by yourself, but it will be very confusing for other developers who see your code.
struct B
{
public int x;
}
struct A
{
public B b;
public int x {
get { return b.x; }
set { b.x = value; }
}
}
}
var a = new A();
a.b.x = 1;
a.x = 1;
However if you switch to classes instead of structs - you can have similar behavior using inheritance:
class B
{
public int x;
}
class A : B
{
}
var a = new A();
a.x = 1;
An embedded Golang struct can be seen as a sort of "inheritance". If you want simulate this behaviour in C# you should use a class instead of struct (here if you want know the difference between struct and class).
Something like this:
public class A {
public int X {get; set;}
}
public class B : A{
B : base() {}
}
...
var a = new B();
a.X = 24;

c# Accessing Creation Class Variables From Instance

Just a basic programming question.
public class ClassA
{
int i = 10;
void Start()
{
ClassB b = new ClassB(this);
b.DoSomething();
}
}
public class ClassB
{
ClassA a;
public ClassB(ClassA a)
{
this.a = a;
}
void DoSomething()
{
Console.WriteLine(a.i);
}
}
I would really like to omit the a:
Console.WriteLine(a.i);
->
Console.WriteLine(i);
What is the most reasonable method of achieving this?
(Note: ClassB must not inherit from ClassA, as ClassA inherits from something ClassB cannot. And I suppose I should say I don't want to pass parameters to the functions, so DoSomething(i) is not applicable.)
You can create a property. Please note that a.i still needs to be public for both your example and mine.
public class ClassB
{
private ClassA a;
public ClassB(ClassA a)
{
this.a = a;
}
public int i { get { return a.i; } }
void DoSomething()
{
Console.WriteLine(i);
}
}

Class inheriting from several Interfaces having same method signature

Say, I have three interfaces:
public interface I1
{
void XYZ();
}
public interface I2
{
void XYZ();
}
public interface I3
{
void XYZ();
}
A class inheriting from these three interfaces:
class ABC: I1,I2, I3
{
// method definitions
}
Questions:
If I implement like this:
class ABC: I1,I2, I3
{
public void XYZ()
{
MessageBox.Show("WOW");
}
}
It compiles well and runs well too!
Does it mean this single method implementation is sufficient for inheriting all the three Interfaces?
How can I implement the method of all the three interfaces and CALL THEM?
Something Like this:
ABC abc = new ABC();
abc.XYZ(); // for I1 ?
abc.XYZ(); // for I2 ?
abc.XYZ(); // for I3 ?
I know it can done using explicit implementation but I'm not able to call them. :(
If you use explicit implementation, then you have to cast the object to the interface whose method you want to call:
class ABC: I1,I2, I3
{
void I1.XYZ() { /* .... */ }
void I2.XYZ() { /* .... */ }
void I3.XYZ() { /* .... */ }
}
ABC abc = new ABC();
((I1) abc).XYZ(); // calls the I1 version
((I2) abc).XYZ(); // calls the I2 version
You can call it. You just have to use a reference with the interface type:
I1 abc = new ABC();
abc.XYZ();
If you have:
ABC abc = new ABC();
you can do:
I1 abcI1 = abc;
abcI1.XYZ();
or:
((I1)abc).XYZ();
During implementation in a class do not specify modifier o/w you will get compilation error, also specify the interface name to avoid ambiguity.You can try the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCSharp
{
class Program
{
static void Main(string[] args)
{
MyClass mclass = new MyClass();
IA IAClass = (IA) mclass;
IB IBClass = (IB)mclass;
string test1 = IAClass.Foo();
string test33 = IBClass.Foo();
int inttest = IAClass.Foo2();
string test2 = IBClass.Foo2();
Console.ReadKey();
}
}
public class MyClass : IA, IB
{
static MyClass()
{
Console.WriteLine("Public class having static constructor instantiated.");
}
string IA.Foo()
{
Console.WriteLine("IA interface Foo method implemented.");
return "";
}
string IB.Foo()
{
Console.WriteLine("IB interface Foo method having different implementation. ");
return "";
}
int IA.Foo2()
{
Console.WriteLine("IA-Foo2 which retruns an integer.");
return 0;
}
string IB.Foo2()
{
Console.WriteLine("IA-Foo2 which retruns an string.");
return "";
}
}
public interface IA
{
string Foo(); //same return type
int Foo2(); //different return tupe
}
public interface IB
{
string Foo();
string Foo2();
}
}

Categories