Dmytro
Dmytro

Reputation: 17176

Is it possible to create extension operators in C#?

So the basic idea was:

We have some business model

public class Model
{
    public int Foo { get; set; }
}

And it's view model representation

public class ViewModel
{
    public string Foo { get; set; }

    public static explicit operator ViewModel(Model b)
    {
        // Map instances using AutoMapper or whatever
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

Our basic instinct is to map model to view model. As you can see I want to perform mapping using explicit operator so I could do

var model = new Model { Foo = 42 }; // Get model
var viewModel = (ViewModel)model;   // Map to view model

and therefore have my controller code as clean as possible... BUT I want to make view model and mapping logic stay separated. How can I move explicit operator implementation to some external class? Similar to extension methods:

public static class Extensions
{
    public static explicit operator ViewModel(Model b)
    {
        // Map instances using Automapper or whatever
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

This code, obviously, isn't compiling because of two reasons:
- Static classes can not contain user-defined operators
- Either parameter or return type must be Extensions

Also, as an option, I could make view model partial and split model itself and operator to separate .cs files but it would not make the case. Architecturally they would still be the same class in the same namespace. I want to be able to implement mapping logic, for example, in another project in solution.

I just want to achieve similar to extension methods effect. How can I do that?

Upvotes: 7

Views: 1163

Answers (2)

InBetween
InBetween

Reputation: 32760

Why not do it the way MS does it in the System.Linq namespace; there is tons of type conversions that are done through extension methods (you can't do it with operators, C# does not support extension operators).

Define the following extension method:

public static class Extensions
{    
    public static ViewModel ToViewModel(this Model model) {...}
}

I think the code remains clean enough which seems to be your primary goal here.

Upvotes: 2

astef
astef

Reputation: 9498

There's nothing better than just:

public class ModelToViewModelMapper
{
    public ViewModel Map(Model b)
    {
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

Extension methods can do the same work, but what if you want to change the mapping logic. It will be easy if you use dependency injection and non-static classes

Upvotes: 5

Related Questions