Friday, April 30, 2021

C# typeof operator and GetType()

C# typeof operator is used to check the type of a data type or its alias passed as argument at compile time. The typeof() operator can take bounded or unbounded type as its parameter. The term unbound type refers to a nongeneric type or an unbound generic type.

The types of the C# language are divided into two main categories: value types and reference types. Both value types and reference types may be generic types, which take one or more type parameters. Type parameters can designate both value types and reference types. Microsoft Doc

using System;

namespace Console_typeofExamples
{
    class Program
    {
        enum Direction { North, South, East, West }

        static void Main(string[] args)
        {
            Console.WriteLine(typeof(int));
            Console.WriteLine(typeof(long));
            Console.WriteLine(typeof(float));
            Console.WriteLine(typeof(double));
            Console.WriteLine(typeof(char));
            Console.WriteLine(typeof(bool));
            Console.WriteLine(typeof(string));
            Console.WriteLine(typeof(Program));
            Console.WriteLine(typeof(Direction));
            Console.WriteLine(typeof(Array));
            Console.WriteLine(typeof(Enum));
            Console.WriteLine(typeof(int[]));
            Console.WriteLine("\nGetType() to get type of a variable or Object");
            int x = 20;
            float y = 30.5f;
            Console.WriteLine(x.GetType());
            Console.WriteLine(y.GetType());

        }
    }
}

OUTPUT

System.Int32
System.Int64
System.Single
System.Double
System.Char
System.Boolean
System.String
Console_typeofExamples.Program
Console_typeofExamples.Program+Direction
System.Array
System.Enum
System.Int32[]

GetType() to get type of a variable or Object
System.Int32
System.Single

No comments:

Post a Comment

Hot Topics