In the class we are dealing with generics and asked to complete the task.
We created an Account<T> class with one private T _balance; and then had to write methods for lending and debiting _balance .
Credit method (partial) called from Main, for example. 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 on int,float and decimal. } _balance = (T)balanceObject; }
I had to check the state and throw, because I can not _balance += (T)balanceObject; as this will give the error "Operator '+' cannot be applied to operand of type 'T'"
During my reading on this subject, I discovered a dynamic type. In my new Account class, I added a new method and changed the Credit method to: (called from Main, for example, 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 do not understand. The credit method accepts the object as a dynamic type, and ConvertType(object input) returns it as a type T Why does using a dynamic type allow me to use operators for generics?
source share