Problem with Abstract class, Interface, Container and methods - c#

I've the following scenario
I've an Interface
public interface ImyInterface
{
void myInterfaceMethod(string param);
}
I've an Abstract Class
public abstract class myAbstractClass
{
public myAbstractClass()
{
//something valid for each inherited class
}
public void myAbstractMethod<T>(T param)
{
//something with T param
}
}
I've a class that inherits from myAbstractClass and implements ImyInterface
public class myClass : myAbstractClass, ImyInterface
{
public myClass():base()
{}
public void ThisMethodWillNeverCall()
{
// nothing to do
}
}
And, finally, I've a class where I'll create a ImyInterface object. At this point I would call myAbstractMethod, but...
public class myFinalClass
{
public void myFinalMethod()
{
ImyInterface myObj = _myContainer<ImyInterface>();
myObj.???
}
}
Obviously there isn't this method because it isn't declared into the interface.
My solution is the following
public interface ImyInterface
{
void myInterfaceMethod(string param);
void myFakeMethod<T>(T param);
}
public class myClass : myAbstractClass, ImyInterface
{
public myClass():base()
{}
public void ThisMethodWillNeverCall()
{
// nothing to do
}
//--- a fake method
public void myFakeMethod<T>(T param)
{
base.myAbstractMethod<T>(param);
}
}
Is there any other solution better than mine?
Thank you!

First of all, your naming convention is a mess. Read up on the guidelines that Microsoft have made.
It's also hard to tell what you are trying to achieve based on your example.
Back to your question:
You should only access an interface to work with that interface. Don't try to make any magic stuff with classes/interfaces to get them working together. That usually means that the class shouldn't try to implement the interface.
It's better that you create a new interface which have the features that you want and let your class implement both.

Related

C# Class Dependency Injection

i need to do something like this in c#. But in the Exec(object) i got a compilation error.
public class ParentClass { }
public class class1 : ParentClass
{
}
public class class2 : ParentClass
{
}
public class class3 : ParentClass
{
}
public class MasterClass
{
public void ExecutionMethod(ParentClass myObject)
{
//some code
Exec(myObject);
//some code
}
public void Exec(class1 obj)
{
//some code
}
public void Exec(class2 obj)
{
//some code
}
public void Exec(class3 obj)
{
//some code
}
}
I solved using Reflection but i think must be a better approach, somebody could give me a nice idea
As #ScottChamberlain pointed out in the comments, you don't have any methods that take an argument of type ParentClass.
Take a look at the Liskov substitution principle - if you've done your implementation properly, you can substitute an instance of, for example, class1 for an instance of ParentClass, but the converse is not true at all.
Odds are, you don't need (or want) the overloads anyway. Just have ParentClass be an abstract class with an abstract Execute method that all child classes have to implement, then you can just call Execute on the class directly without bothering with the overloads. Even better, just make ParentClass an interface. (This is sometimes called the Strategy Pattern by the way).
public interface IParent {
void Execute();
}
public class class1 : ParentClass {
//Execute method implementation
}
public class class2 : ParentClass {
// ...
}
public class class3 : ParentClass {
// ....
}
public class MasterClass
{
public void ExecutionMethod(IParent myObject)
{
//some code
myObject.Execute();
//some code
}
}
I suggest you have a look at object-oriented design patterns. Specifically, the strategy pattern for this problem. Anyway, you can implement what you want like this:
public interface IParent
{
void Exec();
}
public class Child1 : IParent
{
void Exec() { /*code*/ }
}
public class Child2 : IParent
{
void Exec() { /*code*/ }
}
public class Child3 : IParent
{
void Exec() { /*code*/ }
}
public class MasterClass
{
public void ExecutionMethod(IParent myObject)
{
//some code
myObject.Exec();
//some code
}
}
You could also use an abstract class instead of an interface, if you wanted the parent class to have some functionality for the Exec method - then the child classes would have to override the method.
You can use command pattern, with dependency injection. I kind of give you an idea below. The concrete implementation will call execute on your receiver ( you logic goes there
public interface ICommand
{
void Execute();
}
public class Command1 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class Command2 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class Command3 : ICommand
{
public void Execute()
{
throw new NotImplementedException();
}
}
public class CommandManager
{
//you should use DI here to inject each concerete implementation of the command
private Dictionary<string, ICommand> _commands;
public CommandManager()
{
_commands = new Dictionary<string, ICommand>();
}
public void Execute(string key)
{
_commands[key].Execute();
}
}
The error your seeing is a result of your class1,2,3 objects being cast as their parent type because of the signature of the ExecutionMethod(xxx).
And not having an overridden method of Exec that takes a type of 'ParentClass' as the argument.
Probably the simplest method is to create an interface:
IDomainObject{}.
public class ParentClass : IDomainObject { }
public void ExecutionMethod(IDomainObject myObject)
{
Exec(myObject);
}
Using the interface in this way will prevent the downcast during the method call.
You need to use an interface here
Try changing ParentClass like this:
public interface IParentClass{}
Then make each of your classes implement it, like this:
public class class1 : IParentClass
{
}
public class class2 : IParentClass
{
}
Then in your MasterClass, try this:
public void ExecutionMethod(IParentClass myObject)
{
//some code
Exec(myObject);
//some code
}
public void Exec(IParentClass obj)
{
//some code
}
And then you can pass in any of your classes that implement the IParentClassinterface.
Now as an enhancement - if you want every implementation of IParentClass to have some methods and properties that you can invoke in your Exec method, do it like so:
public interface IParentClass
{
void DoTheThing();
}
This will force you to have this method in derived classes, so for example, class1 would look like this:
public class class1 : IParentClass
{
public void DoTheThing()
{
// things get done...
}
}
public class class2 : IParentClass
{
public void DoTheThing()
{
// things get done a different way...
}
}
And now in your Exec method, you can invoke like so:
public void Exec(IParentClass obj)
{
obj.DoTheThing();
}

AutoFac Resolve CommandHandlers from specific derived services

Note: This is similar to this Question
My Question is if I have interfaces defined like below:
(NOTE: My code has more than one derived level; example for simplicity)
public interface IHandler
{
void Handle(IBaseCommand command);
}
public interface IHandler<out T> : IHandler where T : IBaseCommand { }
public interface IBaseCommand { }
public interface IDerivedCommand : IBaseCommand { }
public class BaseCommand : IBaseCommand { }
public class DerivedCommand : IDerivedCommand { }
public class BaseCommandHandler : IHandler<IBaseCommand>
{
public void Handle(IBaseCommand command) { }
}
public class DerivedCommandHandler : IHandler<IDerivedCommand>
{
public void Handle(IBaseCommand command) { }
public void Handle(IDerivedCommand command) { }
}
My snippet of registrations for this example looks like:
builder.RegisterType<DerivedCommand>().AsImplementedInterfaces();
builder.RegisterType<BaseCommand>().AsImplementedInterfaces();
builder.RegisterType<DerivedCommandHandler>().AsImplementedInterfaces();
builder.RegisterType<BaseCommandHandler>().AsImplementedInterfaces();
This container.Resolve<IEnumerable<IHandler<IBaseCommand>>>(); only returns BaseCommandHandler.
I need to get BaseCommandHandler and all derived types, which in this instance would include DerivedCommandHandler too.
I realize this registration container.Resolve<IEnumerable<IHandler>>(); will resolve ALL handlers but I need to be able to resolve any where in the derived chain.
QUESTION: How do I resolve all handlers starting from a specific derived service?
You chould change this:
IHandler<out T>
to:
IHandler<in T>

Can a method in a generic abstract base class "know" the most-derived class of its instance?

I'm trying to figure out if this is possible:
public abstract class A<T>
{
public void MyFunc() { ... }
}
public MyClass : A<string>
{
}
Is there a way for MyFunc to know that it has been instanced in a clas of type MyClass ?
I think I need to clarify the question some more:
I have a generic abstract class that contains some core functionality accessed through a singleton.
The user is building a derived class to extend functionalities but the class is not instantiated through a new, but rather by the singleton, contained in the A class once it is accessed.
So, you could see the flow as such:
In the beginning, there is the abstract A<T>
The user creates MyClass : A<string>
The user now accesses: MyClass.MyFunc()
The singleton in MyFunc is then creating the instance
The singleton code is as follows:
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> _Instance = new Lazy<T>(CreateInstanceOfT);
protected static T Instance => _Instance.Value;
private static T CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
}
}
so:
class A<T>
is really:
class A<T> : Singleton<A>
but what I really need is to, somehow, make it like
Singleton<MyClass>
or whatever class is deriving from
A<T>
I hope this clarifies the question.
Yes, you could do something like:
public abstract class A<T>
{
public void MyFunc()
{
if(this.GetType() == typeof(MyClass))
{
// do your magic
}
}
}
public class MyClass : A<string>
{
}
but why?
Seems to me, if I read your question right, that if the instance of A needs to have MyFunc act differently when it is a MyClass, then MyFunc should be virtual, and overridden in MyClass.
public abstract class A<T>
{
public virtual void MyFunc() { ... }
}
public MyClass : A<string>
{
public override void MyFunc() { ... }
}

Can I omit interface methods in abstract classes in C#?

I'm a Java developer who's trying to move into C#, and I'm trying to find a nice equivalent to some Java code. In Java, I can do this:
public interface MyInterface
{
public void theMethod();
}
public abstract class MyAbstractClass implements MyInterface
{
/* No interface implementation, because it's abstract */
}
public class MyClass extends MyAbstractClass
{
public void theMethod()
{
/* Implement missing interface methods in this class. */
}
}
What would be a C# equivalent to this? The best solutions using abstract/new/override etc all seem to result in 'theMethod' being declared with a body of some form or another in the abstract class. How can I go about removing reference to this method in the abstract class where it doesn't belong, whilst enforcing it's implementation in the concrete class?
You cannot, you would have to do it like this:
public interface MyInterface
{
void theMethod();
}
public abstract class MyAbstractClass : MyInterface
{
public abstract void theMethod();
}
public class MyClass : MyAbstractClass
{
public override void theMethod()
{
/* Implement missing interface methods in this class. */
}
}
No you would have to still have the method signature in the abstract class, but implement it in the derived class.
e.g.
public interface MyInterface
{
void theMethod();
}
public abstract class MyAbstractClass: MyInterface
{
public abstract void theMethod();
}
public class MyClass: MyAbstractClass
{
public override void theMethod()
{
/* implementation */
}
}

How can I factor out the code duplication here?

So, I'd like to hear what you all think about this.
I have a project where three different inheritance paths need to all implement another base class. This would be multiple inheritance and isn't allowed in C#. I am curious how I can implement this without code duplication.
EDIT: I don't own the three classes. The three classes are from 3rd party code. So I cannot make them all extend my base class.
Right now I am using three different classes, each one extending a different base class. Then I have the same code in each of the three abstract classes.
I could use a single interface, but I would still need to duplicate the code.
I could make some kind of static class that implements the code and then reference that in each of the 3 abstract classes. It would eliminate the duplication, but, I am not sure how I feel about this. I could implement Extensions methods on the interface, but then the interface itself would be empty and the extension methods (containing the duplicate code) would be in a totally different file, which seems not quite right. Plus I can't implement properties in extension methods...
How can I factor out the code duplication here?
EDIT, inheritance tree:
class Class1 : 3rdPartyBaseClass1 { }
class Class2 : 3rdPartyBaseClass2 { }
class Class3 : 3rdPartyBaseClass3 { }
I have code I want to be in each of the above Classes, but I cannot add it to the 3rdPartyClasses.
Create an interface that Class1, Class2, and Class3 can implement. Then put your code in extension methods so it will apply to all.
interface IMyInterface {
void Foo(); //these are the methods that these
//classes actually have in common
void Bar();
}
public class Class1 : 3rdPartyBaseClass1, IMyInterface {
// whatever
}
public static class IMyInterfaceExtensions {
public static void CommonMethod(this IMyInterface obj) {
obj.Foo();
obj.Bar();
}
}
public static class Program {
public static void Main() {
var instance = new Class1();
instance.CommonMethod();
}
}
OK, you can do something similar to my previous suggestion, and also similar to recursive's suggestion. For the functionality you require in all three of your derived classes, you can create a single Interface along with a single class (call it "Implementer" for kicks) that implements that Interface (and that has the actual code you want executed with each call).
In each of your derived classes, then, you implement the Interface and create a private instance of Implementer. In each of the interface methods, you just pass the call along to the private instance of Implementer. Because Implementer and your derived classes all implement your Interface, any changes you make to the Interface will require you to modify Implementer and the derived classes accordingly.
And all your code is in one place, except for all the lines passings the calls on to the private instance of Implementer (obviously multiple inheritance would be better than this, but you go to war with the army you have, not the army you wish you had).
Update: what about just adding a public instance of your class to each of the derived classes?
public class DerivedClass1 : ThirdPartyClass1
{
public MyClass myClass = new MyClass();
}
Or if you care who Demeter is and you get paid by LOC:
public class DerivedClass1 : ThirdPartyClass1
{
private MyClass _myClass = new MyClass();
public MyClass myClass
{
get
{
return _myClass;
}
}
}
Then you'd just call the MyClass methods like this:
DerivedClass1 dc1 = new DerivedClass1();
dc1.myClass.DoSomething();
This way, we could all go to sleep.
Similar to MusiGenesis's suggestion, if you need the functionality of the 3rd party classes but do not have to descend from them, you could use composition as follows:
class ThirdPartyBaseClass1
{
public void DoOne() {}
}
class ThirdPartyBaseClass2
{
public void DoTwo() { }
}
class ThirdPartyBaseClass3
{
public void DoThree() { }
}
abstract class Base
{
public void DoAll() { }
}
class Class1 : Base
{
public void DoOne() { _doer.DoOne(); }
private readonly ThirdPartyBaseClass1 _doer = new ThirdPartyBaseClass1();
}
class Class2 : Base
{
public void DoTwo() { _doer.DoTwo(); }
private readonly ThirdPartyBaseClass2 _doer = new ThirdPartyBaseClass2();
}
class Class3 : Base
{
public void DoThree() { _doer.DoThree(); }
private readonly ThirdPartyBaseClass3 _doer = new ThirdPartyBaseClass3();
}
This also gives you the freedom to define whatever interfaces you want and implement them on your classes.
Sounds like you need to insert the new abstract class into the inheritance tree at whatever point those three paths come together, but there really isn't enough information to tell. If you could post some of your inheritance tree, that would help a lot.
I think you may want to use composition instead of inheritance. Exactly how to do this depends on what the third party classes look like, and what your own code looks like. Some more specific code relating to your problem would be helpful, but for example, suppose you want to have three different third party GUI widgets that all need to be customized with your own initializer code.
Case 1: Suppose your third party widgets look like:
public interface IThirdPartyWidget {
public void doWidgetStuff();
}
public class ThirdPartyWidget1: ThirdyPartyWidget implements IThirdPartyWidget {
...
}
public class ThirdPartyWidget2: ThirdPartyWidget implements IThirdPartyWidget {
...
}
You can do:
public class MyWidget implements IThirdPartyWidget {
private IThirdPartyWidget delegateWidget;
public MyWidget(IThirdPartyWidget delegateWidget) {
this.delegateWidget = delegateWidget;
}
public void doWidgetStuff() {
delegateWidget.doWidgetStuff();
}
}
Case 2: Suppose you absolutely need to extend those widgets, and you have to refactor your own code:
public class MyWidget1: ThirdPartyWidget1 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
public class MyWidget2: ThirdPartyWidget2 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
This can become:
public class MyCodeRunner {
public void runMyCode() {
//...
}
}
public class MyWidget1: ThirdPartyWidget1 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
public class MyWidget2: ThirdPartyWidget2 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
Hope this makes sense!

Categories