I'm looking at different patterns and techniques for implementing logic to convert object from one class to another, and the most elegant seems to be explicit cast operator overloading (in C#). However, it seems to me that it violates the Dependency Inversion principle, as it requires one concrete class to have references to another concrete class.
Is this assessment accurate? Is it problematic? Is there a way to implement explicit cast operator overloading without violating the DI principle?
public class Model
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public class ViewModel
{
public string PropOne { get; set; }
public static explicit operator ViewModel(Model model)
{
// Conversion logic that references both classes
}
}
public class Program
{
public void Main()
{
var model = new Model{ Prop1 = "SomeValue", Prop2 = "SomeOtherValue" };
var viewModel = (ViewModel) model;
Console.WriteLine(viewModel.PropOne); // Outputs "SomeValue" to the console
Console.ReadKey();
}
}