I just began work on a large c# code base. Several classes in the code are almost identical to others, which is a question in and of itself, and need to be converted in order to reuse existing logic.
Currently in the code there are extention methods scattered around which take a bit of effort to find and figure out what they are called in order to use them. I would like to move all the convert methods into the class so that they could very easily be found and used. However, I am not sure what is the most accepted way of converting one data type to another when you have the source for everything.
In order to convert ClassA to ClassB should I:
- add a method to ClassA,
- create a ClassAHelper,
- use an extention method for ClassA?
Code to convert one class to another (I assume you’re talking about runtime conversions) may not be the necessary way to go. For example, if you have class X and class Y that each have
void Blah()that you wish to invoke from method C, and method C takes X as a parameter, what you might instead do is extract a common interface for X and Y and then have C accept the interface instead. Therefore your Y can remain Y.Another option is to use the adapter pattern which can make Y conform to the extracted interface of X, and this is particularly useful if Y has the same general functionality but under a different name, or if changing the code of one of the classes is painful, impossible, or simply undesired.
An example, given
You can write
So wherever you have a method that takes
ICanBlahand you have an object of typeY, you can wrap it in an adapter and then pass the adapter to the method.On the other hand, if you really want to do a runtime conversion of X to Y or Y to X, you can define implicit or explicit conversion operators for one or both.
(This operator would need to be declared in the source file of one of the types.)