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?
The ' |= ' symbol is the bitwise OR assignment operator.
In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...
The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.
When using dynamic
types, 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
:
At compile time, an element that is typed as dynamic is assumed to support any operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With