Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 216

C#.Net Generics

Generics is not a completely new concept, similar concept exist with other languages also. In C++, templates can be compared to generics. Generics allow you to define a class with some specific data type at compile time. A generic class can be defined using angle brackets <>.

Example 1: C#.Net Generic

namespace ConsoleApplication1
{
    class example<t>
    {
        public void square(t num)
        {
            if (num.GetType().ToString() == "System.Int32")
            {
                int n = Convert.ToInt32(num.ToString());
                Console.WriteLine("Square of 10 is " + n * n);
            }
            else
            {
                Console.WriteLine("Invalid Number:" + num);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            example<int> ex = new example<int>();
            ex.square(10);
            
            example<string> ex2 = new example<string>();
            ex2.square("abc");
            
            Console.ReadKey();
        }
    }
}
generics
Advertisement
Updated: 10-Sep-21