43
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.

Generics

  • Upload
    bsankar

  • View
    870

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Generics

ge ner ic⋅ ⋅– ad jec t i ve Also, ge ne r i ca l .⋅ ⋅ ⋅ 1 .of, applicable to, or referring to all the members of a genus, class, group, or kind; general.

Page 2: Generics

“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.

Page 3: Generics

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

Page 4: Generics

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.

Page 5: Generics

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.

Page 6: Generics

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).

Page 7: Generics

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

Page 8: Generics

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:

Page 9: Generics

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.

Page 10: Generics

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.

Page 11: Generics

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 

Page 12: Generics

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

Page 13: Generics

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

Page 14: Generics

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.

Page 15: Generics

Const ra in t 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.

Page 16: Generics

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?

Page 17: Generics

C#public class MySample<T>{      public void DoSometing<K,V>()      {}}

VB .NETPublic Class MySample(Of T)      Public Sub DoSomething(Of K, V)()      End SubEnd Class

Page 18: Generics

C#MySample<string> someSample;

VB .NETsomeSample As MySample(Of String)

Page 19: Generics

C# public class MyExample<V>

      {private MySample<V> someSample;}

VB .NET    Public Class MyExample(Of V)      Private someSample As MySample(Of V)    End Class

Page 20: Generics

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.

Page 21: Generics

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

Page 22: Generics

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

Page 23: Generics

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.

Page 24: Generics

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.

Page 25: Generics

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.

Page 26: Generics

C#public T DoSomething<T>(T input, string input2) {

 T tempVar;

}

VB .NETPublic Function DoSomething(Of T)(ByVal input As T, _

ByVal input2 As String) As T            Dim tempVar As T;      End Function

Page 27: Generics

System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following: Dictionary

List

Queue

SortedDictionary

Stack

Page 28: Generics

Generics in VB.NET are very dangerous if you do not put Opt ion St r i c t 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

Page 29: Generics

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.

Page 30: Generics

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 Ob jec t  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.

Page 31: Generics

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.

Page 32: Generics

Code Conso l i da t i on .  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.

Page 33: Generics

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.

Gener i c Algor i t hms. 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 IComparab le .

Page 34: Generics

IDE Suppor t .   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.

Page 35: Generics

Since generics without constraints are perceived by the compiler to be Sys tem.Objec t types, you cannot access any type members not available to System.Ob jec t 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.

Page 36: Generics

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 "Col<T>" is our first indication that this Type is generic. This Type placeholder "T" 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 "T".

Notice on the next line the variable declaration "T t;" 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 "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.

Page 37: Generics

Use of the Previous type in a Classpublic class ColMain { public static void Main()

{ //create a string version of our generic class Col<string> mystring = new Col<string>(); mystring.Val = "hello"; //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()); }

}

Page 38: Generics

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;}}

} }

Page 39: Generics

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="Rob" + x; user.Age=x;users.Add(user);

}

Page 40: Generics

Public class Dictionary<K, V> where K : IComparable {} Notice the "where" 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.

Page 41: Generics

Another type of constraint is a constructor constraint: public class Something<V> where V: new() {}

Page 43: Generics