Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>0) Using .NET's generic collections with your types as container types: Suppose you want to list all the accounts associated with a specific customer, and display them in a data grid. A <code>List&lt;IBankAccount&gt;</code> would be helpful, or a <code>Dictionary&lt;ICustomerID,IBankAccount&gt;</code> if you wanted to look at more than one customer's account.</p> <p><strong>1,2) Creating your own generic class and generic methods</strong>: Say you want to perform a calculation which involves all accounts in order to generate a report. In this particular report, numerical precision is not important, and speed is. So you could use <code>Single</code> insted of <code>Decimal</code>. In this particular case, to make the classes involved in the calculation independent of the numeric type used, using a generic argument is more natural than inheritance. Pseudo code:</p> <pre><code>public class MetricCalculator&lt;T&gt;{ private bool _dirty; private T _cachedValue; T PerformCalculation(){ if( !_dirty ) return cachedValue; T metric = 0; foreach( IBankAccount account in AccountMapper.GetAll() ){ T += account.Foo * accound.Bar; } _cachedValue = metric; return metric; } } </code></pre> <p>In this example, MetricCalculator is a generic class because one of its data members is of the parameterized type. That member is used to avoid repeating the calculation if the values used haven't changed. There is also a generic method, which performs calculations without caring about the numeric type used. If there were no need to cache the value, you could have just a common class with a generic method. I combined both just to save space.</p> <p><strong>3) Generic interface:</strong> Suppose you want to completely decouple all your components (to implement <a href="http://martinfowler.com/articles/injection.html" rel="nofollow noreferrer">Inversion of Control</a>, for example) ; in that case, if you had generic classes like <code>MetricCalculator</code> that were used across assemblies, you'd need to use them via a generic interface. Another example would be if you needed to write a custom data structure or iterator, but I doubt you'd have to come to that.</p> <p><strong>4) Generic events:</strong> Back to the <code>MetricCalculator</code> example, suppose that you want to notify some observer object with an event that notifies that the calculation is done, and pass the result. It would be like an usual event, but you'd pass an argument of type <code>T</code> when raising the event. <strong>Note</strong>: it might be better to use C#5's <a href="https://stackoverflow.com/questions/4057359/new-c-sharp-await-feature">async-await</a> feature if available.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload