Reputation: 9591
Does c# (any version) offer an improved way to alias a property name? In AccountBase, I use the string Username to identify the account, but in NonstandardAccount I want the client (consumer of the API) to use CustomerNumber to prevent confusion.
Here is my code:
public abstract class AccountBase
{
public string Username { get => Username; set => Username = value; }
}
public class StandardAccount
{
// The username is the ID
}
public class NonstandardAccount : AccountBase
{
// The Username or CustomerNumber is the ID
public string CustomerNumber { get => Username; set => Username = value; }
// OR ideally, but I don't think this works
public string CustomerNumber => Username;
}
I could forgo adding a CustomerNumber property and just document that it is the same as the Username, but it isn't clear. I could just leave my implementation as is, but extra storage for the sake of clarity may not be a good tradeoff.
Upvotes: 6
Views: 2774
Reputation: 9591
Thanks to Patrick Artner, I found not only an answer, but the ideal answer. It was right in my source code all along, but I didn't trust my intuition.
public class NonstandardAccount : AccountBase
{
// Does work and works perfectly! Username is still accessible
public string CustomerNumber => Username;
}
A new hard learnt lesson: Just because your intuition was wrong on many occasions, doesn't mean you should discredit it as a pathological liar.
Upvotes: 6