Generics
Upcoming SlideShare
Loading in...5
×
 

Generics

on

  • 1,407 views

 

Statistics

Views

Total Views
1,407
Views on SlideShare
1,405
Embed Views
2

Actions

Likes
1
Downloads
46
Comments
0

2 Embeds 2

http://www.slideshare.net 1
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Generics Generics Presentation Transcript

  • ge⋅ner⋅ic –adjective  Also,  ge⋅ner⋅i⋅cal. 1. of, applicable to, or referring to all the members of a genus, class, group, or kind; general.
    • “ Generic", unrelated to the programming world, it simply means something that is not tied to any sort of brand name.
    • For example, if we purchase some generic dish soap, soap that has no brand name on it, we know that we are buying dish soap and expect it to help us clean our dishes. We can treat it as dish soap even though we don't really have any idea of its exact contents.
    • Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
    • You can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations
    • Generics are a new feature in version 2.0 of the common language runtime (CLR).
    • Generics use the new keyword  Of
    • By creating a generic class, you can create a collection that is type-safe at compile-time.
    • Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot.
    • The most basic type of a collection is an array;
      • however, arrays can be difficult to use, particularly when the number of items in the array varies and when the actual items in the array vary or move around.
      • To address these limitations, we have
    • Collections,
      • which are more or less friendly wrappers around arrays. More important, they enable us to interact with collections of types in a familiar way, just as we might interact with a collection of items in the real world.
    • The problem with collections in the first version of .NET is that in order for them to be strongly typed, the developer would have to write custom collections for each and every type, overriding or implementing methods (such as Add, Remove, Contains, etc.) and indexers on each one
    • Life was also hard for the computer because in order to generalize collection types enough, it had to use the Framework base class, Object, in order to provide the needed flexibility. Value types had to put them into a special package known as a boxing in order to store them in the collection (because the collection was of the Object type, which is a reference type).
    • Any reference or value type that is added to an ArrayList is implicitly upcast to Object .
    • If the items are value types, they must be boxed when they are added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations decrease performance ; the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collections
    • The other limitation is lack of compile-time type checking; because an ArrayList casts everything to Object , there is no way at compile-time to prevent client code from doing something such as this:
    • Use generic types to maximize code reuse, type safety, and performance.
    • The most common use of generics is to create collection classes.
    • The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic  namespace. These should be used whenever possible in place of classes such as ArrayList  in the  System.Collections  namespace.
    • Can create custom own generic interfaces, classes, methods, events and delegates.
    • Generic classes may be constrained to enable access to methods on particular data types.
    • Information on the types used in a generic data type may be obtained at run-time by means of reflection.
    • What a "type" is in .NET
      •   "Type" is simply short hand for "type of data" or "data type"; a type tells the computer how to store information (data) and what will be done with that information.
    •   What Is meant by strongly typed?
      • means that the computer has enough information-a clear blueprint-on how to deal with particular data 
    • What is Type Parameter
      • A type parameter is the core of enabling generic functionality.
      • For types, it is kind of like a constructor parameter.
      • For methods, it's like other parameters except that it can often be inferred
    • What is Generic Type?
      • A definition of a class, structure, interface, procedure, or delegate for which you supply at least one data type when you declare it.
    • What is Generic method? 
      • A generic method is any method that defines one or more type parameters, as in the DoSomething method
      • It is important to note that generic methods do not have to be declared within generic types
    • Type Parameter
      • In a generic type definition, a placeholder for a data type you supply when you declare the type.
    • Type Argument
      • A specific data type that replaces a type parameter when you declare a constructed type from a generic type.
    • Constraint
      • A condition on a type parameter that restricts the type argument you can supply for it.
      • A constraint can require that the type argument must implement a particular interface, be or inherit from a particular class, have an accessible parameter less constructor, or be a reference type or a value type. You can combine these constraints, but you can specify at most one class.
    • What is Constructed Type?
      • This means a type that is created (constructed) as a result of the usage of a generic type.
      • A class, structure, interface, procedure, or delegate declared from a generic type by supplying type arguments for its type parameters.
    • What are called Closed constructed types?
      • At design-time we know the type that is being passed to it
    • What are called open constructed types?
    • C#
      • public class MySample<T>
      • {
      •        public void DoSometing<K,V>()
      •        {}
      • }
    • VB .NET
      • Public Class MySample(Of T)
      •        Public Sub DoSomething(Of K, V)()
      •        End Sub
      • End Class
    • C#
    • MySample<string> someSample;
    • VB .NET
    • someSample As MySample(Of String)
    • C#
      • public class MyExample<V>
      •        {private MySample<V> someSample;}
    • VB .NET
      •      Public Class MyExample(Of V)
      •        Private someSample As MySample(Of V)
      •      End Class
    • What is Constrain in .NET Generics?
      • That enable the creator of a generic to specify that only certain types may be passed in as type arguments to his generic.
    • C#
      •        public class MyClass<T, K> {
      •          public void DoSomething() {
      •                    T temp = new T();
      •                   Debug.Assert(temp.Contains(“test”)); }}
    • VB .NET
        •        Public Class MyClass(Of T, K)
        •              Public Sub DoSomething()
        •                    Dim temp As T = New T()
        •                   Debug.Assert(temp.Contains(“test”))
        •              End Sub
        •        End Class
    • C#
      •        public class MyClass<T,K> where T: IList, new() where K: Icomparable {
      •              public void DoSomething() {
      •                    T temp = new T();
      •                    Debug.Assert(temp.Contains(“test”)); } }        
    • VB .NET
      •        Public Class MyClass(Of T As {New, IList}, K As IComparable)
      •              Public Sub DoSomething()
      •                    Dim temp As T = New T()
      •                    Debug.Assert(temp.Contains(“test”))
      •              End Sub
      •        End Class
    • Constraints are specified by using the  where  contextual keyword
    Constraint Description where T: struct The type argument must be a value type. Any value type except  Nullable  can be specified. See  Using Nullable Types (C# Programming Guide)  for more information. where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the  new()  constraint must be specified last.
  • where T : <base class name> The type argument must be or derive from the specified base class. where T : <interface name> The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic. where T : U The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
    • Which are simply methods that have type parameters. Generic methods are useful in many situations, particularly where you need the return type to be variable as in, e.g., factory methods.
    • Methods are another exciting field of use for Generics. Generic methods will allow you to pass one or more data types.
    • C#
        • public T DoSomething<T>(T input, string input2) {
        •   T tempVar;
        • }
    • VB .NET
    • Public Function DoSomething(Of T)(ByVal input As T, _
    • ByVal input2 As String) As T
    •              Dim tempVar As T;
    •        End Function
    • System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following:
      • Dictionary
      • List
      • Queue
      • SortedDictionary
      • Stack
    • Generics in VB.NET are very dangerous if you do not put  Option Strict On  at the beginning of your code or as your default in the configuration. VB.NET has a tendency to autocast if strict is not on
    • Generics has the following advantages:
      • The Program becomes statically typed, so errors are discovered at compile-time.
      • No runtime casts are required and the program runs faster.
      • Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
    • Type Safe:
      • Generic types enforce compile-time type checking. This greatly reduces, if not eliminates, unhanded run-time exceptions due to data type conflicts
      • Types based on  Object  accept any data type, and you must write code to check whether an input data type is acceptable. With generic types, the compiler can catch type mismatches before run time.
    • Re-usability :
      • A class written with Generics is reusable, no need duplicating classes for different data types
    • Performance:
      • Since the data type is determined at compile-time there is no type casting at run-time
      • Generic types do not have to  box  and  unbox  data, because each one is specialized for one data type.
    • Code Consolidation.  
      • The code in a generic type has to be defined only once.
      • A set of type-specific versions of a type must replicate the same code in each version, with the only difference being the specific data type for that version.
      • With generic types, the type-specific versions are all generated from the original generic type.
    • Code Reuse.  
      • Code that does not depend on a particular data type can be reused with various data types if it is generic. You can often reuse it even with a data type that you did not originally predict.
    • Generic Algorithms.
      • Abstract algorithms that are type-independent are good candidates for generic types. For example, a generic procedure that sorts items using the  IComparable  interface can be used with any data type that implements  IComparable .
    • IDE Support.  
      • When you use a constructed type declared from a generic type, the integrated development environment (IDE) can give you more support while you are developing your code.
      • For example, IntelliSense can show you the type-specific options for an argument to a constructor or method.
    • Since generics without constraints are perceived by the compiler to be System.Object types, you cannot access any type members not available to System.Object nor can you use arithmetic operators or nested classes.
    • Cannot access static members or nested classes without explicitly casting.
    • Cannot use arithmetic operations unless the base class specified in the constraints list supports them.
    • Cannot use generics themselves as type arguments, but, you can use constructed types as type arguments.
    • Creating Generic Type
      • public class Col<T> { T t; public T Val{get{return t;}set{t=value;}}
        • There are a few things to notice.
      • The class name &quot;Col<T>&quot; is our first indication that this Type is generic.
      • This Type placeholder &quot;T&quot; is used to show that if we need to refer to the actual Type that is going to be used when we write this class, we will represent it as &quot;T&quot;.
      • Notice on the next line the variable declaration &quot;T t;&quot; creates a member variable with the type of T, or the generic Type which we will specify later during construction of the class (it will actually get inserted by the Common Language Runtime (CLR) automatically for us).
      • The final item in the class is the public property. Again, notice that we are using the Type placeholder &quot;T&quot; to represent that generic type for the type of that property. Also notice that we can freely use the private variable &quot;t&quot; within the class.
    • Use of the Previous type in a Class
    • public class ColMain
    • {
    • public static void Main()
      • { //create a string version of our generic class
      • Col<string> mystring = new Col<string>();
      • mystring.Val = &quot;hello&quot;; //output that value System.Console.WriteLine(mystring.Val); System.Console.WriteLine(mystring.Val.GetType()); //create another instance of our generic class, using a different type
      • Col<int> myint = new Col<int>();
      • myint.Val = 5;
      • System.Console.WriteLine(myint.Val);
      • System.Console.WriteLine(myint.Val.GetType());
    • }
    • }
    • For this example we want to be able to hold a collection of a Type that we create, which we used to represent a User in our system. Here is the definition for that class:
      • namespace Rob
      • {
        • public class User
        • {
            • protected string name;
            • protected int age;
            • public string Name{get{return name;}set{name=value;}}
            • public int Age{get{return age;}set{age=value;}}
        • }
      • }
    • Now that we have our User defined, let's create an instance of the .NET Framework Generic version of a simple List:
    • System.Collections.Generic.List<Rob.User> users = new System.Collections.Generic.List<Rob.User>();
      • For ( int x=0;x<5;x++)
        • {
          • Rob.User user = new Rob.User();
          • user.Name=&quot;Rob&quot; + x;
          • user.Age=x;
          • users.Add(user);
        • }
    • Public class Dictionary<K, V> where K : IComparable {}
    • Notice the &quot;where&quot; clause on this class definition. It is forcing the K Type to be of Type IComparable.
    • If K does NOT implement IComparable, you will get a Compiler error.
    • Another type of constraint is a constructor constraint:
    • public class Something<V> where V: new() {}
    • http://www.vbdotnetheaven.com
    • http://www.c-sharpcorner.com
    • http://www.15seconds.com
    • www.15seconds.com
    • http://blogs.msdn.com/kcwalina
  •