0

I have a class with two different properties that map to the same value:

class MyClass {
    public int Number { get; set; }
    public string NumberString {
        get { return Number.ToString(); }
        set { Number = int.Parse( value ); }
    }
}

The second property (here NumberString) simply gets or sets the first property (here Number) using a different type. The code is rather trivial, but results in a lot of boilerplate code when I have many of these "buddy" properties.

Is it possible to do the conversion using a custom property? I would prefer if I could write the second property something like this:

[MapsTo(nameof(Number))]
public string NumberString { get; set; }

The attribute should then be able to do the conversion for me (maybe based on some rules I make depending on type).

I have the impression that this could be done with something like PostSharp, but is it possible with custom attributes?

Mikkel R. Lund
  • 2,336
  • 1
  • 31
  • 44
  • 1
    No - not yet, at least. There's a potential future C# language feature around this sort of thing, but it's not there yet. – Jon Skeet Feb 10 '17 at 10:20
  • 1
    No it's not possible in general, as you describe, with just custom attributes. PostSharp is the way to go. – Evk Feb 10 '17 at 10:20
  • Use Reflection to do that for yourself, check whether an attribute is applied and tweak the property value – Mrinal Kamboj Feb 10 '17 at 10:29

0 Answers0