C # common code between classes

In Visual Studio 2008 using C #, what is the best way to share code between multiple classes and source files?

Inheritance is not a solution, because classes already have a meaningful hierarchy.

Is there some neat feature similar to a C-containing file that allows you to embed code anywhere in another class?

EDIT:

ok, I think we need a concrete example ...

There are several hundred classes in the domain with a well-designed class hierarchy. Now many of these classes have to print. There is a service printer class that handles printing. Say there are 3 different printing methods that depend on the printable class. The code that invokes the print method (6 lines) is that I try to avoid copying and pasting on all pages of the client class.

It would be nice if people did not assume that they know more about the domain in question, especially when they specifically mention methods that are not suitable ...

+4
source share
10 answers

If you have functionality that you often use in classes representing very different things, in my experience, which should fall into several categories:

  • Utilities (e.g. line formatting, parsing, ...)
  • General issues (logging, security, ...)

For functions such as utilities, you should consider creating separate classes and links to utility classes, if necessary in a business class.

public class Validator { public bool IsValidName(string name); } class Patient { private Validator validator = new Validator(); public string FirstName { set { if (validator.IsValidName(value)) ... else ... } } } 

For cross-cutting tasks such as logging or security, I suggest you study Aspect Oriented Programming .

Regarding the example of PrintA vs. PrintB, discussed in other comments, this looks like a great example for the Factory pattern. You define an interface, for example. IPrint, the PrintA and PrintB classes that implement IPrint, and assign an IPrint instance based on a specific page.

 // Simplified example to explain: public interface IPrint { public void Print(string); } public class PrintA : IPrint { public void Print(string input) { ... format as desired for A ... } } public class PrintB : IPrint { public void Print(string input) { ... format as desired for B ... } } class MyPage { IPrint printer; public class MyPage(bool usePrintA) { if (usePrintA) printer = new PrintA(); else printer = new PrintB(); } public PrintThePage() { printer.Print(thePageText); } } 
+7
source

The C # utility class will work. It acts as a central registry for common code (or as a constructor for the VB.NET module) - it must contain code that does not belong to any class, otherwise it should be bound to the corresponding class.

You do not want to start copying the source code if you do not need it, as this will lead to problems with updating the code taking into account duplication .

As long as the source does not need to maintain state, use a static class with a static method.

 static public class MySharedMembers { static public string ConvertToInvariantCase(string str) { //...logic } // .... other members } 
+3
source

You cannot just load the code you want to add to a class in C # using the preprocessor directive, as in C.

However, you can define an interface and declare extension methods for that interface. After that, the interface can be implemented by your classes, and you can call extension methods for these classes. For instance.

 public interface IShareFunctionality { } public static class Extensions { public static bool DoSomething(this IShareFunctionality input) { return input == null; } } public class MyClass : Object, IShareFunctionality { public void SomeMethod() { if(this.DoSomething()) throw new Exception("Impossible!"); } } 

This will allow you to reuse the functionality, but you cannot access the private members of the class, as it would be possible if you could, hash, include the file.

We may need some more concrete examples of what you want to do, though?

+3
source

If classes are in the same namespace, there is no need to include analog. Just call class members defined in another function.

If they are not in the same namespace, add the namespace of the classes that you want to use in the usings directives, and it should work the same as above.

I am confused by the question: it seems you need to work on your basic understanding of OO.

+2
source

I don’t know how to include parts of files, but we often do so to add an existing file and “link” it to the current location. For example, we have an assemblyInfo.cs file, to which each project from the solution catalog belongs. We change it once, and all projects have the same information, because they belong to the same file.

Otherwise, suggestions for refactoring "regular" routines in common.dll are the best thing I came up with .Net.

+2
source

I'm not sure exactly what you mean by a “meaningful” structure, but it seems like a place where you could use a base class implementation. Although not as verbose as C ++ multiple inheritance, you can benefit from using a chained base class implementation to reuse common functions.

You can maintain the class hierarchy, at least visually, and override the behavior as needed.

+1
source

Pull the duplicate code into services. Duplicate code is the key to what may be the place for refactoring.

For example, create a "PrintingService" that contains the logic needed for printing. Then you can have classes that need to print, be dependent on this service (either using the constructor, or using a parameter that requires the service).

Another tip I have on these lines is to create interfaces for basic functions, and then use interfaces for coding. For example, I had a group of report classes that the user could send by fax, email, or print. Instead of creating methods for each, I created a service for everyone if they implemented an interface in which there was a single Output () method. Then I could transfer each service to the same method depending on what type of product the user needs. When a client wanted to use eFax instead of faxing via modem, it was just a matter of writing a new service that implemented the same interface.

+1
source

Honestly, I can't come up with anything like this in Visual C #, and also why you want this feature. However, partial classes may do something like what sounds the way you want, but using them may be related to your requirement "classes already have a meaningful hierarchy."

0
source

You have many options: TT, extension method, delegate and lambda

0
source

All Articles