What does generics in c#

Definition :

Generics means allows to defining a class or method without particular any data type. It is a improve performance, productivity and type-safety. It is also said parametric polymorphism. It is most commonly use with collections like linked lists, arrays, stacks, queues, hash tables, enumerable queryable, trees etc. Perform operations such as add and delete items from the collection with regardless of the data type.

Benefits :

  • Casting is not required for accessing items from the collection
  • Type-safe while execution
  • Reusable code for multiple types of data
  • Improve the performance and productivity
  • Boxing and Unboxing are not required

Where List<T> collection class is an example for generic class that can be used for add, remove and search an item of any type (T) that passed as parameter to it.

Examples :

   class SampleClass1<T> : IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

    class SampleClass2<T> where T : IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

    class SampleClass3<T> : IDisposable where T : IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

    class SampleClass4<T>
    {
        public IEnumerable<T> GetList()
        {
            return new List<T>();
        }

        public IEnumerable<T> GetStack()
        {
            return new Stack<T>();
        }

        public IEnumerable<T> Paginate(IEnumerable<T> list, int Page, int PageSize)
        {
            return list.Skip(Page * PageSize).Take(PageSize);
        }
    }

Comments

Popular posts from this blog

Get OAuth 2.0 access token of Paypal using HttpClient in c#

Generics method using interface in c#

Match substring surrounded by known prefix and suffix using regex in c#