In class we have being dealing with generics and were asked to complete an assignment.
We created an Account<T> class with one property private T _balance; and then had to write methods to credit and debit _balance.
Credit method (partial) called from Main by e.g. acc1.Credit(4.6);:
public void Credit(T credit)
{
Object creditObject = credit;
Object balanceObject = _balance;
Type creditType = creditObject.GetType();
Type balanceType = balanceObject.GetType();
if(creditType.Equals(balanceType))
{
if(creditType.Equals(typeof (double)))
{
balanceObject= (double)balanceObject + (double)creditObject;
}
...WITH more else if's on int,float and decimal.
}
_balance = (T)balanceObject;
}
I had to condition check and cast as I cannot _balance += (T)balanceObject; as this will give the error "Operator '+' cannot be applied to operand of type 'T'"
During my reading on the subject I discovered the dynamic type. In my new Account class I added a new method and changed the Credit method to: (called from Main by e.g. acc1.Credit(4.6);)
public void Credit(dynamic credit)
{
_balance += ConvertType(credit);
}
public T ConvertType(object input)
{
return (T)Convert.ChangeType(input, typeof(T));
}
This is what I don’t understand. The credit method takes in the object as type dynamic and the ConvertType(object input) returns it as type T.
Why does using dynamic type allow me to use operators on generics?
When using
dynamictypes, resolution is deferred until runtime. If, at runtime, the generic type supports a+operator, your code will work. If not, it will throw an exception.From a MSDN article on
dynamic: