Implement method in another project - c#

Is it possible to declare a method's class in a project and implement in another ? Something like :
namespace projectA
{
Class A
{
void toImplement()
{
//TODO
}
void print()
{
toImplement();
}
}
}
namespace projectB
{
A.toImplement()
{
// print “projectB"
}
}
namespace projectC
{
A.toImplement()
{
// print “projectC"
}
}
I don't want to create a new class with inheritance, because I want to use the method in class A. But if I define the method in a project K, the method will do the same that if I call from project B.

You can create an abstract method, but it will have to be public to be accessible in another project:
namespace projectA
{
public abstract Class A
{
public abstract void toImplement();
}
}
namespace projectB
{
public Class B : A
{
public override void toImplement()
{
//Implement here
}
}
}

You can write an Extension function see MSDN: Extension Function
For just adding methods to it, - as you described in your second code example - you could use a partial class
public static class B_Extensions
{
public static void SetString(this A a, string s)
{
a.Astring = s;
}
}
public class A
{
public string Astring { get; set; }
}
// In any other class
private void DoSomething()
{
var a = new A();
a.SetString("Something");
}
Partial Class: - put those in the same project
public partial class A
{
public void SetString(string s)
{
Astring = s;
}
}
public partial class A
{
public string Astring { get; set; }
}

So my guess is the reason you don't want to make A abstract and implement it in the other projects is because you want to be able to do new A() in the library.
In this case, the solution therefore, is to use the Factory Pattern.
You make the method abstract, and you declare a factory interface.
namespace projectA {
Class A
{
abstract void toImplement();
}
Interface AFactory
{
A create()
}
}
Then in your project that uses this you have your implementation of A and make a factory.
namespace projectB
{
Class RealA extends A
{
void toImplement() { does stuff }
}
Class RealAFactory implements AFactory
{
A create() { return new RealA() }
}
}
You now just need to pass the factory to the library when initalising it or at some logically point in time. Now projectA can get a new instance of RealA whenever it needs from RealAFactory.

Related

How to implement a factory pattern based on argument types?

I have PhotoBase class
public abstract class PhotoBase
{
public string Path { get; set; }
}
And I have multiple derived classes, for example the path may indicate a location in the file system or an external url.
public class FilePhoto : PhotoBase {}
public class ExternalPhoto : PhotoBase {}
I want to load these photos, I have a PhotoLoader class like below:
public class PhotoLoader
{
public void Load(FilePhoto Photo)
{
// get the photo from file system
}
public void Load(ExternalPhoto Photo)
{
// download the photo from path
}
}
Now I want to load these photos, so I have to do:
public class PhotoImporter
{
private PhotoLoader _photoLoader;
public PhotoImporter(PhotoLoader photoLoader)
{
_photoLoader = photoLoader;
}
public void ImportPhoto(PhotoBase photo)
{
if (photo is FilePhoto)
{
_photoLoader.Load(photo as FilePhoto);
}
if (photo is ExternalPhoto)
{
_photoLoader.Load(photo as ExternalPhoto);
}
}
}
I have several derived classes and I may add more photo types in the future. Is there a more elegant way that I could get rid of if conditions? Using factory pattern?
Another approach would be to have an abstract method Load on PhotoBase, that's then implemented by each subclass:
public abstract class PhotoBase
{
public string Path { get; set; }
public abstract void Load();
}
public class FilePhoto : PhotoBase
{
public override void Load()
{
// load from file system
}
}
public class ExternalPhoto : PhotoBase
{
public override void Load()
{
// load from path
}
}
That way, you can simply call the Load method on a PhotoBase:
public class PhotoImporter
{
public void ImportPhoto(PhotoBase photo)
{
photo.Load();
}
}
The main advantage is that each subclass implements the Load method, and therefore you can add as many subclasses as you want, without worrying about forgetting to implement it.
The main drawback to this implementation is that the Load methods can't depend on other dependencies. So for example, if one day you need to load a photo from a database, you can't pass the DBContext.
Proper to way to implement it which will make code easy to maintain is as follows:
public abstract class PhotoBase
{
public string Path { get; set; }
public abstract void Load(); // Have a abtract method
}
public class FilePhoto : PhotoBase {
public override void Load() { // Implement the abtract method
Console.WriteLine("FilePhoto");
}
}
public class ExternalPhoto : PhotoBase {
public override void Load() { // // Implement the abtract method
Console.WriteLine("ExternalPhoto");
}
}
public class PhotoLoader
{
private PhotoBase _PhotoBase;
public PhotoLoader(PhotoBase photoBase) { // Resolved by Dependency Injection
_PhotoBase = photoBase;
}
public void Load()
{
_PhotoBase.Load();
}
}
public class PhotoImporter
{
private PhotoLoader _photoLoader;
public PhotoImporter(PhotoLoader photoLoader) // Resolved by Dependency Injection
{
_photoLoader = photoLoader;
}
public void ImportPhoto()
{
_photoLoader.Load();
}
}
You need to have Dependency Injection define so that specified implementation will get resolved and appropriate 'Load' method will be invoked.
void Main()
{
// Following dependency should be resolved by Dependency Injection
PhotoBase filePhotoBase = new FilePhoto();
PhotoLoader filePhotoLoader = new PhotoLoader(filePhotoBase);
PhotoImporter filePhotoImporter = new PhotoImporter(filePhotoLoader);
PhotoBase externalPhotoBase = new ExternalPhoto();
PhotoLoader externalPhotoLoader = new PhotoLoader(externalPhotoBase);
PhotoImporter externalPhotoImporter = new PhotoImporter(externalPhotoLoader);
filePhotoImporter.ImportPhoto(); // Shows output 'FilePhoto'
externalPhotoImporter.ImportPhoto(); // Shows output 'ExternalPhoto'
}
You can have as much implementation as you want, but you need to have proper instance of PhotoImporter by Dependency Injection. Everything else will work smoothly.
This is how I could do this:
public class PhotoImporter
{
private PhotoLoader _photoLoader;
public PhotoImporter(PhotoLoader photoLoader)
{
_photoLoader = photoLoader;
}
public void ImportPhoto(PhotoBase photo)
{
var childType = photo.GetType();
dynamic childPhoto = Convert.ChangeType(photo, childType);
_photoLoader.Load(childPhoto);
}
}
You can simplify your ImportPhotoby using pattern matching:
public void ImportPhoto(photoBase photo)
{
switch(photo)
{
case FilePhoto filePhoto:
loader.Load(filePhoto);
break;
case ExternalPhoto externalPhoto:
loader.Load(externalPhoto);
break;
}
}
But this is only syntactic sugar and doesn't solve your real problem. What might help is a abstract Load method in your base class:
public abstract class PhotoBase
{
public string Path { get; set; }
public abstract void Load();
}
You have to implement this method in your child classes. If you call the method, the correct implementation will be chosen.
Online demo: https://dotnetfiddle.net/LfkxBQ

Multiple inheritance using interaces

Please consider the attached figure.
What I want is that the (technical-) "User" can use methods from class A, B or C by an instantiate of "HeadClass". What I try to avoid is, that I have to add a separate function for each method defined in Class A, B and C to call them through the "HeadClass". I tried to describe this in an other stackoverflow-request yesterday but have deleted it because it seemed to be unclear what I wanted to achieve. So here is an other approach.
Usually this would be achieved by inheritance (if only one class would be inherited from). But, as they told me in that deleted post, I should use Interface instead. Now, so far I thought that I know how interface work (using almost for every class), but I can't figure how I achieve this describe problem.
How would I have to fill the "???" in "HeadClass"?
I am happy for any input. Thx in adavnce!
class User
{
public User(IHeadClass headObj)
{
_headObj = headObj
}
public DoStuff()
{
_headObj.Method_1
_headObj.Method_2
_headObj.HeadMethod
}
}
public class HeadClass : IHeadClass, ???
{
???
public HeadClass( ??? )
{
???
}
void HeadMethod()
{
... do head stuff
}
}
public class Class_A : IClass_A
{
public void Method_1 () { }
}
public class Class_B : IClass_B
{
public void Method_2 () { }
public void Method_3 () { }
}
public class Class_C : IClass_C
{
public void Method_4 () { }
}
I have check out this describing how to use interfaces instead. But this doesn't solve the above problem.
If I understand correctly you can use composition here. Something like this:
public interface IClass_A
{
void Method_1 ();
}
public interface IClass_B
{
void Method_2 ();
void Method_3 ();
}
public interface IClass_C
{
void Method_4 ();
}
public interface IHeadClass : IClass_A, IClass_B, IClass_C
{
void HeadMethod();
}
public class HeadClass : IHeadClass
{
private readonly IClass_A _a;
private readonly IClass_B _b;
private readonly IClass_C _c;
public HeadClass(IClass_A a, IClass_B b, IClass_C c)
{
_a = a;
_b = b;
_c = c;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1() => _a.Method_1();
public void Method_2() => _b.Method_2();
public void Method_3() => _b.Method_3();
public void Method_4() => _c.Method_4();
}
C# (unlike for example C++ or PHP) does not support multiple inheritance. Interfaces allows multiple inheritance, but they don't provide definitions of methods, only declarations.
I think solution could be pattern called fasade: write methods in HeadClass that calls methods in other classes. In this case interfaces are not necessary.
public class HeadClass
{
private Class_A _a;
private Class_B _b;
private Class_C _c;
public HeadClass( Class_A a, Class_B b, Class_C c )
{
_a=a;
_b=b;
_c=c;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1 () {
_a.Method_1();
}
public void Method_2 () {
_b.Method_2();
}
public void Method_3 () {
_b.Method_3();
}
public void Method_4 () {
_c.Method_4();
}
}
May I suggest instead that you have an interface passed instead of Class definition in your constructor?
public class HeadClass
{
private IMethod1 _method1;
private IMethod2 _method2;
private IMethod3 _method3;
private IMethod4 _method4;
public HeadClass( IMethod1 method1, IMethod2 method2, IMethod3 method3, IMethod4 method4)
{
_method1=method1;
_method2=method2;
_method3=method3;
_method4=method4;
}
void HeadMethod()
{
... do head stuff
}
public void Method_1 () {
_method1.Method_1();
}
public void Method_2 () {
IMethod2.Method_2();
}
public void Method_3 () {
IMethod3.Method_3();
}
public void Method_4 () {
IMethod4.Method_4();
}
}
Now you have removed any direct coupling to a class, you are no only linked by interface.
Say you want to split method 2 and 3 into it's own two classes? this code, never has to change.
You can now reuse any class that has a definition of the interface, as a paramater. No code is defined twice, that does the same thing, in each input.
Because:
public class Method1 : IMethod1
{
}
public class Method2 : IMethod2
{
}
public class Method3 : IMethod3
{
}
public class Method4 : IMethod4
{
}
can now be parsed as parameters to HeadClass.
or, if you insist method 2 & 3 belong on the same class.
public class ClassA: IMethod1
{
}
public class ClassB: IMethod2, IMethod3
{
}
public class ClassC: IMethod4
{
}
Should be obvious from this example that the benefits lie in the fact that you can now do whatever you want in Headclass, and if you need behaviour to change, you can inject code via constructor, without having to retry the behaviour of headclass.
And headclass, doesn't know ClassA, B or C exist directly, only the interface.
I Believe this is called the Strategy pattern?

C# Unity how do we resolve/instantiate class for multi level class method calls

I am creating a project in which I need to use unity & resolve class instances, below is a sample of what my classes looks like:
class A
{
public B BInstance { get; set; }
public A()
{
BInstance = new B(??How do I instantiate using unity ??);
}
void M3()
{
BInstance.M2();
}
}
class B
{
public C CInstance { get; set; }
public B(C cInstance)//??How do I instantiate using unity ??
{
CInstance = cInstance;
}
public void M2()
{
CInstance.M1();
}
}
class C
{
public D DInsatnce { get; set; }
public C(D dInstance)//??How do I instantiate using unity ??
{
DInsatnce = dInstance;
}
public void M1()
{
DInsatnce.MTest();
}
}
class D
{
public void MTest()
{
}
}
I don't want to call Unity Resolve under each class (A, B C, D), I can/want to call unity resolve just in ultimate parent class(A). Also I don't feel that passing instance of D, C from class A is good.
So I am looking for best way to instantiate classes C,D which then can be passed through the constructors of callers.
Many thanks in advance!!!
All you need here is to mark BInstance property of class A with [Dependency] attribute and instantiate A with new UnityContainer().Resolve<A>().
Constructor parameters are instantiated by default, if they can be resolved.

Dynamically combine classes in order to remove responsibilities from API

I'm building an API (for a game-engine) which exposes two interfaces called IWindow and IEngineWindow.
The IWindow interface is supposed to be implemented by an API-user and the IEngineWindow interface is used by the engine to interact with the window.
The window object should have a private member of the type List<IWindowControl>.
I could use an abstract class and get rid of the interfaces but then i would have implementation-details in my API which i don't want.
My theoretical solution to the problem is that the API-user implements IWindow in his own class and calls a method (something like GetEngineWindow(typeof(MyWindowClass))) which returns an object which is identical to an instance of MyWindowClass except that it also implements the IEngineWindow interface.
I was planning to use System.Reflection.Emit in the GetEngineWindow() method to dynamically combine MyWindowClass with an internal class which implements the IEngineWindow interface but i quickly realised that this would be a mayor project of it's own.
My question boils down to if there is a simpler solution to remove this kind of implementation-details from an API or if there exists a library (free for commercial use) to do this kind of class-fusing.
In case my question is too abstract, here is a code example of what i want to be able to do:
//API (dll-file)
interface IWindow
{
void BeforeClose();
}
interface IEngineWindow
{
void Show();
}
//Built into engine (written by me)
class Program
{
static void Main(string[] args)
{
object window = CombineClasses(typeof(Testwindow), typeof(EngineWindow));
((IWindow)window).BeforeClose(); //Outputs: Closing...
((IEngineWindow)window).Show(); //Outputs: Showing window...
}
}
class EngineWindow : IEngineWindow
{
public void Show()
{
Console.WriteLine("Showing window...");
}
}
//External assembly (dll-file)
class Testwindow : IWindow
{
public void BeforeClose()
{
Console.WriteLine("Closing...");
}
}
This sounds like you need a wrapper.
Let your internal class take an IWindow instance in its constructor
store it in a private field
implement both interfaces
and forward all IWindow members to the internal instance
Update: if you consider CastleWindsor a simpler approach, here it is (using xUnit for tests):
namespace Mixins
{
using System;
using Castle.DynamicProxy;
using Xunit;
public interface IA
{
void Do();
}
public interface IB
{
void Something();
}
public class A : IA
{
public void Do()
{
throw new NotImplementedException("A");
}
}
public class B : IB
{
public void Something()
{
throw new NotImplementedException("B");
}
}
public class Blender
{
[Fact]
public void Mix()
{
var options = new ProxyGenerationOptions();
// the instances for A and B would be the user provided and yours
options.AddMixinInstance(new A());
options.AddMixinInstance(new B());
var proxy = new ProxyGenerator().CreateClassProxy<object>(options);
Assert.IsAssignableFrom<IA>(proxy);
Assert.IsAssignableFrom<IB>(proxy);
try
{
((IA)proxy).Do();
}
catch (NotImplementedException ex)
{
if (ex.Message != "A")
{
throw;
}
}
try
{
((IB)proxy).Something();
}
catch (NotImplementedException ex)
{
if (ex.Message != "B")
{
throw;
}
}
}
}
}
I am the author of NCop - A composite-aspect framework that can help you achieve your goal.
NCop wiki
You basically need to create a new composite type interface that will implement both of your window interfaces and mark it as a composite using the TransientComposite attribute.
[TransientComposite]
public interface ICompositeWindow : IWindow, IEngineWindow
{
}
Order NCop to match between interfaces and implementations using Mixins attribute.
[TransientComposite]
[Mixins(typeof(EngineWindow), typeof(Testwindow))]
public interface ICompositeWindow : IWindow, IEngineWindow
{
}
create a CompositeContainer that will emit the new type.
class Program
{
static void Main(string[] args) {
ICompositeWindow window = null;
var container = new CompositeContainer();
container.Configure();
window = container.Resolve<ICompositeWindow>();
window.Show();
window.BeforeClose();
}
}
your final code should be:
using System;
using NCop.Composite.Framework;
using NCop.Mixins.Framework;
using NCop.Composite.Runtime;
namespace NCop.Samples
{
[TransientComposite]
[Mixins(typeof(EngineWindow), typeof(Testwindow))]
public interface ICompositeWindow : IWindow, IEngineWindow
{
}
public interface IWindow
{
void BeforeClose();
}
public interface IEngineWindow
{
void Show();
}
public class EngineWindow : IEngineWindow
{
public void Show() {
Console.WriteLine("Showing window...");
}
}
public class Testwindow : IWindow
{
public void BeforeClose() {
Console.WriteLine("Closing...");
}
}
class Program
{
static void Main(string[] args) {
ICompositeWindow window = null;
var container = new CompositeContainer();
container.Configure();
window = container.Resolve<ICompositeWindow>();
window.Show();
window.BeforeClose();
}
}
}

Derived types with Method overloading

The code is simple enough to understand I hope.
I'm trying to use an interface type IColor in order to pass color objects to the ColorManager. I then want the ColorManager to pass this object to the IColor object as its own type, so the method overloads gets called.
However, it seems since it is being passed as the IColor type, C# will not implicity cast it into its complete type as either a BlueColor or GreenColor.
I hope this makes some sense to somebody on what I want to achieve. Is this possible in C#?
[Solution]
http://msdn.microsoft.com/en-us/library/dd264736.aspx
Overload Resolution with Arguments of Type dynamic
My code so far:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace Example
{
public interface IColor
{
void CatchColor(IColor c);
}
public class BlueColor : IColor
{
public void CatchColor(IColor c)
{
}
}
public class GreenColor : IColor
{
public void CatchColor(BlueColor c)
{
Console.WriteLine("CAUGHT BLUE!");
}
public void CatchColor(GreenColor c)
{
Console.WriteLine("CAUGHT GREEN!");
}
public void CatchColor(IColor c)
{
Console.WriteLine("CAUGHT SOME COLOR!");
}
}
public class ColorManager
{
public void PassColor(IColor c)
{
// Don't use static type-checking
// Problem solved
dynamic AnyColor = c;
AnyColor.CatchColor(AnyColor);
}
public static void Main()
{
GreenColor G = new GreenColor();
new ColorManager().PassColor(G);
Console.ReadLine();
return;
}
}
}
One possiblity to tell the ColorManager class to use the correct type of the passed object is to use an abstract class, that already implements the CatchColor:
public abstract class IColor
{
// override in every class
public abstract void PrintColor();
// has the correct type passed with the interface
public void CatchColor(IColor c)
{
c.PrintColor();
}
}
Then the sub classes need to implement only PrintColor with the correct color:
public class BlueColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("BLUE!");
}
}
public class GreenColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("GREEN!");
}
}
The manager is the same:
public class ColorManager
{
public void PassColor(IColor c)
{
c.CatchColor(c);
}
}
It can be used like this:
GreenColor G = new GreenColor();
var cm = new ColorManager();
cm.PassColor(G);
cm.PassColor(new BlueColor());
The outputs is:
GREEN!
BLUE!
What you want is late method binding.
The downside to this is you have to add methods for each new type of color. The upside is you don't have to maintain a case statement or conditional logic.
See here for more detail:
Early and late binding
Edit: Here is a working example of this type of late-binding.
class Program {
static void Main(string[] args) {
//Declare instances
BaseClass myClass = new Class2();
BaseClass otherClass = new Class1();
//Invoke the action method which will match based on the BaseClass type
Action(myClass);
Action(otherClass);
Console.ReadLine();
}
public static void Action(BaseClass classType) {
//Remove the compile-time type so the runtime can select the method based on signature
dynamic aClass = classType;
ServiceMethod(aClass);
}
public static void ServiceMethod(dynamic input) {
Methods(input);
}
public static void Methods(Class1 classType) {
Console.WriteLine("Class1");
Debug.WriteLine("Class1");
}
public static void Methods(Class2 classtype) {
Console.WriteLine("Class2");
Debug.WriteLine("Class2");
}
public static void Methods(Class3 classType) {
Console.WriteLine("Class3");
Debug.WriteLine("Class3");
}
}
public abstract class BaseClass { //This could also be an interface
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Class1 : BaseClass {
}
public class Class2 : BaseClass{
}
public class Class3 : BaseClass {
}
So you want something like:
public void CatchColor(Color c)
{
if (c is BlueColor)
CatchColor(c as BlueColor);
if (c is GreenColor)
CatchColor(c as GreenColor);
}
?

Categories

Resources