C# Class Dependency Injection - c#

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();
}

Related

How To separate methods from my giant generic class

So I have a very big Generic class 1500+ rows and growing, with loads of methods. It has CrazyMethods and GoodMethods, I want to put the different kinds of methods in their own class but still be able to use my generic as if they were inside the generic class.
public class MyGeneric<T> : IMyGeneric<T> where T : IEntity
{
public MyGeneric(string stuff)
{
moreStuff(stuff);
}
// Region Good
public void MyGoodMethod1(T entity)
{
//does good stuff with the generic..
}
public T MyGoodMethod2()
{
//does other good stuff with the generic..
}
//Region Crazy
public void MyCrazyMethod1(T entity)
{
//does crazy stuff with the generic..
}
public T MyCrazyMethod2()
{
//does other crazy stuff with the generic..
}
}
Now in my other project where I use this generic it looks something like this
...
SomeObject _myObject = new MyGeneric<SomeObject>("ladida");
_myObject.MyGoodMethod1();
//..Other stuff
_myObject.MyCrazyMethod2();ยจ
...
How do I separate the methods from the MyGeneric class into separate classes (MyGenericGoodMethods.cs, MyGenericCrazyMethods.cs) but still be able to use them the way I showcased above ?
If I could use extension methods for generics that would be the perfect solution.
public static class MyGenericGoodMethods<T> where T : IEntity
{
public static T Method2(this MyGeneric<T> generic)
{
//does other good stuff with the generic..
}
}
but
Extension method can only be declared in non generic, non nested, static class
You can declare extension method in normal static class and use it with generic.
public static class MyGenericGoodMethodsExtensions
{
public static T Method2(this MyGeneric<T> generic)
{
//does other good stuff with the generic..
}
}
var myGeneric = new MyGeneric<string>();
myGeneric.Method2()
But you can always split your giant class in many separated generic classes and use them inside your main-generic class.
Split up your interfaces
public interface IMyGeneric<T>
{
void MyGeneric(string stuff);
}
public interface IMyGoodGeneric<T>
{
void MyGoodMethod1(T entity);
void MyGoodMethod2(T entity);
}
public interface IMyCrazyGeneric<T>
{
void MyCrazyMethod1(T entity);
void MyCrazyMethod2(T entity);
}
Introduce separated implementation
public class MyGeneric<T> : IMyGeneric<T> where T : IEntity
{
public void MyGeneric(string stuff)
{
// implementation
}
}
public class MyGoodGeneric<T> : IMyGoodGeneric<T> where T : IEntity
{
public void MyGoodMethod1(T entity) {}
public void MyGoodMethod2(T entity) {}
}
public class MyCrazyGeneric<T> : IMyCrazyGeneric<T> where T : IEntity
{
public void MyCrazyMethod1(T entity) {}
public void MyCrazyMethod2(T entity) {}
}
Then you can create your "giant" composition class which will implement all interfaces and use already existed implementations
public class MyGiantGeneric<T> : IMyGeneric<T>,
IMyGoodGeneric<T>,
IMyCrazyGeneric<T> where T : IEntity
{
private readonly IMyGeneric<T> _myGeneric;
private readonly IMyGoodGeneric<T> _myGoodGeneric;
private readonly IMyCrazyGeneric<T> _myCrazyGeneric;
public MyGiantGeneric(IMyGeneric<T> myGeneric,
IMyGoodGeneric<T> myGoodGeneric,
IMyGCrazyGeneric<T> myCrazyGeneric)
{
_myGeneric = myGeneric;
_myGoodGeneric = myGoodGeneric;
_myCrazyGeneric = myCrazyGeneric;
}
public void MyGeneric(string stuff)
{
_myGeneric.MyGeneric(stuff);
}
public void MyGoodMethod1(T entity)
{
_myGoodGeneric.MyGoodMethod1(entity);
}
// and so on...
}
With this approach your logic will stay in logically separated classes.
In case somewhere you need only MyGoodGeneric method you don't need to provide whole giant class and will provide only the part needed.
In case some where you want introduce another implementation only for the MyCrazy methods you will not be forced to implement MyGood methods which you don't need in this case.
Extension method can be generic, not its container class:
public static class Extensions
{
public static T Method2<T>(this MyGeneric<T> generic)
{
}
}
So Partial classes were exactly what i was looking for. Thanks to #BradleyDotNET and #AliAbdelfattah
public partial class MyGeneric<T> : IMyGeneric<T> where T : IEntity
{
public MyGeneric(string stuff)
{
moreStuff(stuff);
}
//.. other stuff
}
in MyGenericGood.cs
public partial class MyGeneric<T> where T : IEntity
{
public void MyGoodMethod1(T entity)
{
//does good stuff with the generic..
}
public T MyGoodMethod2()
{
//does other good stuff with the generic..
}
}

Refactoring a concrete method in abstract class which contains an abstract method

Considering the below code,
abstract class AbstractClass
{
public abstract void AbstractMethodA();
public void ConcreteMethodA()
{
//Some operation
ConcreteMethodB();
}
}
public void ConcreteMethodB()
{
//Huge code unrelated to this class
AbstractMethodA();
}
}
class DerivedClass : AbstractClass
{
public void AbstractMethodA()
{
//Some operation
}
}
Now I wish to move ConcreteMethodB() to separate class and make a call to this from the method ConcreteMethodA() in abstract class. But since ConcreteMethodB() uses an abstract method AbstractMethodA() implemented in DerivedClass, I am unable to access the method AbstractMethodA() from the new class? Any idea on how to resolve this?
Why don't you make it like this
static class Helper {
public static void ConcreteMethodB(AbstractClass caller)
{
//Huge code unrelated to this class
caller.AbstractMethodA();
}
}
and then in AbstractClass
abstract class AbstractClass
{
public abstract void AbstractMethodA();
public void ConcreteMethodA()
{
//Some operation
Helper.ConcreteMethodB(this);
}
}
Edit including interface based decoupling suggestion from David Arno:
static class Helper {
public static void ConcreteMethodB(IAbstractClass caller)
{
//Huge code unrelated to this class
caller.AbstractMethodA();
}
}
interface IAbstractClass {
void AbstractMethodA();
}
and then in AbstractClass
abstract class AbstractClass
{
public abstract void AbstractMethodA();
public void ConcreteMethodA()
{
//Some operation
Helper.ConcreteMethodB(this);
}
}
That gives you better layers isolation. Of course the solution suggested by David in his post mentioning usage of "Action" and passing method as argument is also worth consideration.
To completely decouple to the two, you could take the "functional" route:
static class Helper
{
public static void ConcreteMethodB(Action caller)
{
//Huge code unrelated to this class
caller();
}
}
The change AbstractClass to:
abstract class AbstractClass
{
public abstract void AbstractMethodA();
public void ConcreteMethodA()
{
Helper.ConcreteMethodB(AbstractMethodA);
}
}

Problem with Abstract class, Interface, Container and methods

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.

Having trouble getting rid of redundant code via inheritance or generics

Sorry for the vague title, but I wasn't sure how to summarize this in one phrase. I have a situation with a lot of redundant C# code, and it really looks like some kind of crafty trick using some property of inheritance or generics would solve this. However, I'm not a terribly experienced programmer (particularly with C#) and just can't quite see the solution.
The situation, in simplified form, looks something like this. I have a bunch of classes that all inherit from one type.
public class Foo : SuperFoo
{
...
public Foo SomeMethod() { ... }
}
public class Bar : SuperFoo
{
...
public Bar SomeMethod() { ... }
}
public class Baz : SuperFoo
{
...
public Baz SomeMethod() { ... }
}
...
public class SuperFoo
{
...
}
The problem comes when collections of these objects need to be processed. My first-draft solution (the bad one) looks like this:
public void SomeEventHasHappened(...)
{
ProcessFoos();
ProcessBars();
ProcessBazes();
...
}
public void ProcessFoos()
{
...
foreach (var foo in fooList)
{
...
foo.SomeMethod();
}
}
public void ProcessBars()
{
...
foreach (var bar in barList)
{
...
bar.SomeMethod();
}
}
...and so on. The problem is that basically all of the code in the ProcessX methods is the same, other than the type of the objects that are being operated on. It would be nice to consolidate all of these into one method for obvious reasons.
My first thought was to just make a generic Process() method that took a List<SuperFoo> as a parameter and just proceed from there. The problem is that a generic SuperFoo does not have a SomeMethod(), and it can't have one because each of the child classes' SomeMethod() has a different return type, so having overrides doesn't work.
I usually add an interface which operates on base types.
interface ISuperFoo
{
public ISuperFoo SomeMethod() { ... }
}
public class Foo : SuperFoo, ISuperFoo
{
// concrete implementation
public Foo SomeMethod() { ... }
// method for generic use, call by base type
public ISuperFoo ISuperFoo.SomeMethod()
{
return SomeMethod();
}
}
public void Processs()
{
...
foreach (var iSuperFoo in list)
{
...
iSuperFoo.SomeMethod();
}
}
Of course it depends what you are using the result for.
Sometimes you can make it easier using generics, but you also can end up in a mess. Sometimes it is just easier to downcast somewhere. Of course, you try to avoid this whenever you can afford it.
Here's an example of how this might work using generics and making SuperFoo an abstract class.
public interface ISuperFoo
{
...
}
public abstract class SuperFoo<T> where T : ISuperFoo
{
public abstract T SomeMethod();
}
public class BazReturn : ISuperFoo
{
...
}
public class Baz: SuperFoo<BazReturn>
{
public override BazReturn SomeMethod()
{
throw new NotImplementedException();
}
}
public class BarReturn : ISuperFoo
{
...
}
public class Bar : SuperFoo<BarReturn>
{
public override BarReturn SomeMethod()
{
throw new NotImplementedException();
}
}
public static class EventHandler
{
public static void SomeEventHasHappened(List<SuperFoo<ISuperFoo>> list)
{
foreach (SuperFoo<ISuperFoo> item in list)
{
ISuperFoo result = item.SomeMethod();
}
}
}
You could replace the ISuperFoo interface with a concrete class if needed, but then you would have to cast the return value which kind of defeats the purpose.
public abstract class SuperFoo<T>
{
public abstract T SomeMethod();
}
public class Foo : SuperFoo<int>
{
public override int SomeMethod()
{
throw new NotImplementedException();
}
}
public static class EventHandler
{
public static void SomeEventHasHappened(List<SuperFoo<int>> list)
{
foreach (SuperFoo<int> item in list)
{
item.SomeMethod();
}
}
}

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.

Categories