Reputation: 23
I want to retrieve BalanceAmount from particular Class. How do i do
public class SettlePendingAmount<T> : Form
{
public T Activity { private get; set; }
private void Initialize()
{
var bal = 0
if (Activity is Invoice)
{
bal = ((Invoice)Activity).BalanceAmount;
}
if (Activity is Purchase)
{
bal = ((Purchase)Activity).BalanceAmount;
}
}
}
Upvotes: 0
Views: 100
Reputation: 38737
I expect you want to use an interface:
public interface IBalance
{
// I inferred int from your var bal = 0;
// if that's incorrect, feel free to change it
int BalanceAmount { get; }
}
Now we'll add a generic constraint on T
:
public class SettlePendingAmount<T> : Form
where T: IBalance
We'll also need to add this interface to Invoice
and Purchase
:
public class Invoice : IBalance
{
public int BalanceAmount { get; } // or get; set; (whatever you currently have)
}
public class Purchase : IBalance
{
public int BalanceAmount { get; } // or get; set; (whatever you currently have)
}
Then we can freely access BalanceAmount:
public class SettlePendingAmount<T> : Form
where T : IBalance
{
public T Activity { private get; set; }
private void Initialize()
{
var bal = Activity.BalanceAmount;
}
}
The downside here is that your SettlePendingAmount
class can only be constructed for types that implement this interface. From the brief outline of what you're doing, I suspect this is OK.
Upvotes: 1