0

Say you have the following code:

interface Foo 
{
    public int Value { get; set; }
}

class Bar : Foo
{
    public int Value { get; set; }
}

Now suppose I'd like to give the Value property a more sensible name in Bar, like BarValue (I can imagine this is not uncommon, since interfaces might have very generalized property names so that the naming in deriving classes is suboptimal for readability). Is it possible to give Value an alias, so the Bar class looks sort of like this:

class Bar : Foo
{
    public int Value as BarValue { get; set; }
}

So that I can access the property like this:

Bar bar = new Bar();

//Calling Value as normal
Console.WriteLine(bar.Value);

//Calling the same property, Value, but using its alias
Console.WriteLine(bar.BarValue);

My question is: is this possible? I know you can achieve the same thing doing it like this:

class Bar : Foo
{
    public int Value { get; set; }
    public int BarValue { get => Value; set => Value = value; }
}

But this is less neat. Thanks in advance.

  • Are you familiar with [explicit interface implementations](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation) in C#? – Kirk Woll Jun 28 '22 at 17:52
  • 3
    Your final code is exactly the right code to use. You have two properties, one of which passes through to another. – Jon Skeet Jun 28 '22 at 17:54
  • @madreflection It is not what I was hoping for, but it does answer my question, thank you! – Jens Steenmetz Jun 28 '22 at 18:01
  • 1
    FWIW, if you were writing Visual Basic, you could call it whatever you wanted and use `Implements Foo.Value`. Under the hood, it includes the `.implements` directive the way explicit implementation in C# does, but allows it on a public member so you don't have to write both members. Maybe you should submit a request that the feature be included in C#. I can't imagine how bad the syntax would have to be, though. – madreflection Jun 28 '22 at 18:03
  • You could also explicitly have the backing fields for the auto-properties be mapped to the same memory using `[field: FieldOffset(N)]`, but that's even less readable than what you already have. – Joe Sewell Jun 28 '22 at 18:18

0 Answers0