• No results found

Generics and Collections 103 

In document CSharp Handout v1.0 (Page 103-113)

Learning Objectives

After completing this session, you will be able to: ‰ Define Generic Types

‰ Describe the Generic Methods ‰ Explain Constraints in Generics

Generics

Generics are classes, structures, interfaces, and methods that have placeholders (type

parameters) for one or more of the types they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects it stores; the type parameters appear as the types of its fields, and the parameter types of its methods. A generic method might use its type parameter as the type of its return value, or as the type of one of its formal parameters. The following code illustrates a simple generic class definition. Generics are most commonly used with collections and the methods that operate on them.

public class Generic<T> {

public T Field; }

Example:

// Declare the generic class public class GenericList<T> {

void Add(T input) { } }

class TestGenericList {

private class ExampleClass { } static void Main()

{

// Declare a list of type int

GenericList<int> list1 = new GenericList<int>(); // Declare a list of type string

GenericList<string> list2 = new GenericList<string>(); // Declare a list of type ExampleClass

GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();

} }

Advantages of Generics:

‰ By allowing you to specify the specific types acted on by a generic class or method, the generics feature shifts the burden of type safety from you to the compiler. ‰ There is no need to write code to test for the correct data type, because it is enforced

at compile time. The need for type casting and the possibility of run-time errors are reduced.

‰ Generics provide type safety without the overhead of multiple implementations.

Constraints on Type Parameters:

‰ When define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code

attempts to instantiate your class with a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified using the where contextual keyword. The following table lists the five types of constraints:

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, including any class, interface, delegate, or array type.

where T : new() The type argument must have a public parameterless constructor. When used in conjunction 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.

Why do you use Constraints?

‰ If you want to examine an item in a generic list to determine whether it is valid or to compare it to some other item, the compiler must have some guarantee that the operator or method it needs to call will be supported by any type argument that might be specified by client code. This guarantee is obtained by applying one or more constraints to our generic class definition

Generic Methods:

‰ A generic method is a method that is declared with type parameters, as follows:

static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; }

The following code example shows one way to call the method, using int for the type argument: Public static void Testswap()

{ Int a=1; Int b=2; Swap<int>(ref a, ref b); System.Console.writeline (a+””+b); } Classes in Generics

The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.Some of the classes in this namespace, are as follows:

S.No Class Description

1 Dictionary Represents a collection of keys and values.

2 List Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

3 Queue Represents a first-in, first-out collection of objects.

4 Stack Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type.

Dictionary Class:

‰ Represents a collection of keys and values. ‰ Namespace:System.Collections.Generic

Assembly: mscorlib (in mscorlib.dll) ‰ Syntax:

[SerializableAttribute] [ComVisibleAttribute(false)]

public class Dictionary<TKey,TValue> : IDictionary<TKey,TValue>,

ICollection<KeyValuePair<TKey,TValue>>,IEnumerable<KeyValuePair <TKey,TValue>>, IDictionary, ICollection, IEnumerable,

ISerializable, IDeserializationCallback

Members:

Public Properties:

S.No Name Description

1 Comparer Gets the IEqualityComparer that is used to determine equality of keys for the dictionary.

2 Count Gets the number of key/value pairs contained in the Dictionary. 3 Item Gets or sets the value associated with the specified key. 4 Keys Gets a collection containing the keys in the Dictionary. 5 Values Gets a collection containing the values in the Dictionary.

Public Methods:

S.No Name Description

1 Add Adds the specified key and value to the dictionary. 2 Clear Removes all keys and values from the Dictionary.

3 ContainsKey Determines whether the Dictionary contains the specified key. 4 ContainsValue Determines whether the Dictionary contains a specific value. 5 Equals Overloaded. Determines whether two Object instances are

equal. (Inherited from Object.)

6 GetEnumerator Returns an enumerator that iterates through the Dictionary. 7 GetHashCode Serves as a hash function for a particular type. GetHashCode is

suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

8 GetObjectData Implements the System.Runtime.Serialization.ISerializable interface and returns the data needed to serialize the Dictionary instance.

9 GetType Gets the Type of the current instance. (Inherited from Object.) 10 OnDeserialization Implements the

System.Runtime.Serialization.ISerializable interface and raises the deserialization event when the deserialization is complete.

11 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

12 Remove Removes the value with the specified key from the Dictionary.

13 ToString Returns a String that represents the current Object. (Inherited from Object.)

Protected Methods:

S.No Name Description

1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

2 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

List Class:

‰ Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

‰ Namespace:System.Collections.Generic Assembly: mscorlib (in mscorlib.dll) ‰ Syntax:

[SerializableAttribute]

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

Members:

Public properties:

S.No Name Description

1 Capacity Gets or sets the total number of elements the internal data structure can hold without resizing.

2 Count Gets the number of elements actually contained in the List. 3 Item Gets or sets the element at the specified index.

Public Methods:

S.No Name Description

1 Add Adds an object to the end of the List.

2 AddRange Adds the elements of the specified collection to the end of the List.

3 AsReadOnly Returns a read-only IList wrapper for the current collection. 4 BinarySearch Overloaded. Uses a binary search algorithm to locate a specific

element in the sorted List or a portion of it. 5 Clear Removes all elements from the List.

6 Contains Determines whether an element is in the List.

7 ConvertAll Converts the elements in the current List to another type, and returns a list containing the converted elements.

8 CopyTo Overloaded. Copies the List or a portion of it to an array. 9 Equals Overloaded. Determines whether two Object instances are

S.No Name Description

10 Exists Determines whether the List contains elements that match the conditions defined by the specified predicate.

11 Find Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List.

12 FindAll Retrieves the all the elements that match the conditions defined by the specified predicate.

13 FindIndex Overloaded. Searches for an element that matches the

conditions defined by a specified predicate, and returns the zero- based index of the first occurrence within the List or a portion of it.

14 FindLast Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire List.

15 FindLastIndex Overloaded. Searches for an element that matches the

conditions defined by a specified predicate, and returns the zero- based index of the last occurrence within the List or a portion of it.

16 ForEach Performs the specified action on each element of the List. 17 GetEnumerator Returns an enumerator that iterates through the List.

18 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

19 GetRange Creates a shallow copy of a range of elements in the source List. 20 GetType Gets the Type of the current instance. (Inherited from Object.) 21 IndexOf Overloaded. Returns the zero-based index of the first occurrence

of a value in the List or in a portion of it.

22 Insert Inserts an element into the List at the specified index.

23 InsertRange Inserts the elements of a collection into the List at the specified index.

24 LastIndexOf Overloaded. Returns the zero-based index of the last occurrence of a value in the List or in a portion of it.

25 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

26 Remove Removes the first occurrence of a specific object from the List. 27 RemoveAll Removes the all the elements that match the conditions defined

by the specified predicate.

28 RemoveAt Removes the element at the specified index of the List. 29 RemoveRange Removes a range of elements from the List.

30 Reverse Overloaded. Reverses the order of the elements in the List or a portion of it.

S.No Name Description

32 ToArray Copies the elements of the List to a new array.

33 ToString Returns a String that represents the current Object. (Inherited from Object.)

34 TrimExcess Sets the capacity to the actual number of elements in the List, if that number is less than a threshold value.

35 TrueForAll Determines whether every element in the List matches the conditions defined by the specified predicate.

Protected Methods:

S.No Name Description

1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

2 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

Queue Class:

‰ Represents a first-in, first-out collection of objects. ‰ Namespace:System.Collections.Generic

Assembly: System (in system.dll) ‰ Syntax:

[SerializableAttribute] [ComVisibleAttribute(false)]

public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable

Members:

Public Properties:

S.No Name Description

1 Count Gets the number of elements contained in the Queue.

Public Methods:

S.No Name Description

1 Clear Removes all objects from the Queue.

2 Contains Determines whether an element is in the Queue.

3 CopyTo Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.

4 Dequeue Removes and returns the object at the beginning of the Queue. 5 Enqueue Adds an object to the end of the Queue.

6 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

S.No Name Description

7 GetEnumerator Returns an enumerator that iterates through the Queue. 8 GetHashCode Serves as a hash function for a particular type. GetHashCode is

suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

9 GetType Gets the Type of the current instance. (Inherited from Object.) 10 Peek Returns the object at the beginning of the Queue without removing

it.

11 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

12 ToArray Copies the Queue elements to a new array.

13 ToString Returns a String that represents the current Object. (Inherited from Object.)

14 TrimExcess Sets the capacity to the actual number of elements in the Queue, if that number is less than 90 percent of current capacity.

Protected Methods:

S.No Name Description

1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

2 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

Stack Class:

‰ Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type.

‰ Namespace: System.Collections.Generic Assembly: System (in system.dll)

‰ Syntax:

[SerializableAttribute] [ComVisibleAttribute(false)]

public class Stack<T> : IEnumerable<T>, ICollection, IEnumerable

Members:

Public Properties

S.No Name Description

Public Methods:

S.No Name Description

1 Clear Removes all objects from the Stack.

2 Contains Determines whether an element is in the Stack.

3 CopyTo Copies the Stack to an existing one-dimensional Array, starting at the specified array index.

4 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

5 GetEnumerator Returns an enumerator for the Stack.

6 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

7 GetType Gets the Type of the current instance. (Inherited from Object.) 8 Peek Returns the object at the top of the Stack without removing it. 9 Pop Removes and returns the object at the top of the Stack. 10 Push Inserts an object at the top of the Stack.

11 ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

12 ToArray Copies the Stack to a new array.

13 ToString Returns a String that represents the current Object. (Inherited from Object.)

14 TrimExcess Sets the capacity to the actual number of elements in the Stack, if that number is less than 90 percent of current capacity.

Protected Methods:

S.No Name Description

1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

2 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

Summary

‰ Generics: Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types they store or use. ‰ Generics Methods: A generic method is a method that is declared with type

parameters.

‰ Constraints: When define a generic class, We can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class

Test Your Understanding 1. What is Generics?

2. How do you define Generics?

3. What are Constraints and how do you specify it? 4. What is Naked Type constraints and where it is used? 5. What is Generic method?

6. How do you declare Generic method? 7. What are the benefits of Generics?

In document CSharp Handout v1.0 (Page 103-113)