What is the typeof() method in C#?

Overview

In C#, we use the typeof() method to get the name of a class in C#. This method is similar to the GetType() method, which helps determine the type of variable. We use the typeof() method with some properties such as Name, FullName, and Namespace. The Name property returns the name of the class, FullName returns the name of the class along with its namespace, and Namespace returns the namespace only.

Syntax

typeof(class)
// OR
typeof(class).property
Syntax for the typeof() method

Parameters

class: We want to determine the name of this class.

property: We use any of the properties listed above.

Return value

The value returned is a string denoting the name of a particular class.

Example

using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// for int
Console.WriteLine("Class int...");
Console.WriteLine("Name: " + typeof(int).Name);
Console.WriteLine("FullName: " + typeof(int).FullName);
Console.WriteLine("Namespace: " + typeof(int).Namespace);
Console.WriteLine();
// for char
Console.WriteLine("Class char...");
Console.WriteLine("Name: " + typeof(char).Name);
Console.WriteLine("FullName: " + typeof(char).FullName);
Console.WriteLine("Namespace: " + typeof(char).Namespace);
Console.WriteLine();
// for bool
Console.WriteLine("Class bool...");
Console.WriteLine("Name: " + typeof(bool).Name);
Console.WriteLine("FullName: " + typeof(bool).FullName);
Console.WriteLine("Namespace: " + typeof(bool).Namespace);
Console.WriteLine();
// for double
Console.WriteLine("Class double...");
Console.WriteLine("Name: " + typeof(double).Name);
Console.WriteLine("FullName: " + typeof(double).FullName);
Console.WriteLine("Namespace: " + typeof(double).Namespace);
Console.WriteLine();
}
}
}

Explanation

  • Lines 11–15: We print the name of the class for int its Fullname, and namespace.
  • Lines 18–22: We print the name of the class for char, its Fullname, and namespace. We'll repeat it for classes bool and double.

    Free Resources