C# "Rename" Property in Derived Class
Posted
by
Eric
on Stack Overflow
See other posts from Stack Overflow
or by Eric
Published on 2012-09-07T21:28:17Z
Indexed on
2012/09/07
21:38 UTC
Read the original article
Hit count: 221
When you read this you'll be awfully tempted to give advice like "this is a bad idea for the following reason..."
Bear with me. I know there are other ways to approach this. This question should be considered trivia.
Lets say you have a class "Transaction" that has properties common to all transactions such as Invoice, Purchase Order, and Sales Receipt.
Let's take the simple example of Transaction "Amount", which is the most important monetary amount for a given transaction.
public class Transaction
{
public double Amount { get; set; }
public TxnTypeEnum TransactionType { get; set; }
}
This Amount may have a more specific name in a derived type... at least in the real world. For example, the following values are all actually the same thing:
- Transaction - Amount
- Invoice - Subtotal
- PurchaseOrder - Total
- Sales Receipt - Amount
So now I want a derived class "Invoice" that has a Subtotal rather than the generically-named Amount. Ideally both of the following would be true:
- In an instance of Transaction, the Amount property would be visible.
- In an instance of Invoice, the Amount property would be hidden, but the Subtotal property would refer to it internally.
Invoice looks like this:
public class Invoice : Transaction
{
new private double? Amount
{
get
{
return base.Amount;
}
set
{
base.Amount = value;
}
}
// This property should hide the generic property "Amount" on Transaction
public double? SubTotal
{
get
{
return Amount;
}
set
{
Amount = value;
}
}
public double RemainingBalance { get; set; }
}
But of course Transaction.Amount is still visible on any instance of Invoice.
Thanks for taking a look!
© Stack Overflow or respective owner