NET Centric Computing - Old Questions

9. Why do we need generics? What are the significances of MSIL?

5 marks | Asked in Model Question

Generic is common to write a program that processes a collection - e.g. a collection of numbers, a collection of contacts, a collection of Name, etc. With generic programming, we can write code that handles a collection 'in the general' and C# handles the specifics for each collection type, saving you a great deal of work.

Generic collection in C# is defined in System.Collection.Generic namespace. It provides a generic implementation of standard structure like List, Stack, Queues, Dictionaries etc.

E.g.

using System;  

using System.Collections.Generic;  

public class GenericList  

{  

    public static void GenericListMethod()  

    {  

        List<int> genericList = new List<int>(); 

        // No boxing, no casting:  

        genericList.Add(12);  

        genericList.Add(13);  

        genericList.Add(14);  

        genericList.Add(15);   

    

There are mainly two reasons to use generics as in the following:

1. Performance: Collections that store the objects uses boxing and unboxing on data types. A collection can reduce the performance. By using generics it helps to improve the performance and type safety.

2. Type Safety: there is no strong type information at compile time as to what it is stored in the collection.


Microsoft Intermediate Language (MSIL)

During the compile time , the compiler convert the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native code. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System.

When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Meatdata. The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.