Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>o.k.w., Simply put, Generics are faster and give you a much more flexible approach to working with a strongly typed language such as C# . You are giving the compiler a compile time size hint (it won't have to discover it during run-time) that it is to contain some class 'T' List. But this just the beginning . . you can have generic classes and methods . . . you can limit the type by using the where statement. Here's an example (no, I didn't compile it . . it won't compile . . this is strictly for demo purposes only) sorry if it's real clear . . .it's getting past my bedtime!</p> <pre><code>Called like: </code></pre> <p>CoolOps op = new CoolOp();</p> <pre><code> IOtherCoolInterace oci = DoThisVeryCoolThing&lt;IOtherCoolInterace,CoolOps&gt;(op); public T DoThisVeryCoolThing&lt;T,U&gt;(U whatIAm) where U: IMyVeryCoolInterface where T: IOtherCoolInterface // I'm restricting the type that can be operated on and returned { T thingToReturn = default(T); if(whatIAm == null) return thingToReturn; try { thingsToReturn = whatIAm.DoSomeWorkOnTheInterface(); } catch(Exception ex) { ... // do exception stuff here } return thingToReturn; // return work done } public interface IMyVeryCoolInterface { IOtherCoolInterface DoSomeWorkOnTheInterface(); . . . } // My operation must implement this interace public class CoolOps : IMyVeryCoolInterface { . . . IOtherCoolInteface DoSomeWorkOntheInterface() { return xxx; } } </code></pre> <p>etc etc...</p> <p>What this does it to do some work on an instance of U that must implement an interface (my contract!) IMyVeryCoolInterface and that interface contains a method call that returns an object instance that must implment IOtherCoolInterface.<br> How does this work in the real world? This lets you set up a general approach to doing work with many different types. So, if you had a number of classes that described opertions, work on those operations can be called in a 'generic' fashion as above. This avoids repetitive mistake prone code where similar methods are written over and over again that do only a very slightly different operation based on a type(different algorithms for an image blur for example) - but just in slightly different fashion. e.g. ** We know we are going to do an image operation on an image but lets parametrize the image type (jpeg,png, etc) and algorithm (5x5, 3x3 convolution etc) and write the method once ** Or something to that effect . . . </p> <p>I hope this helps . . . </p> <p>TheEruditeTroglodyte</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