Use Of C# TypeOf Operator
In C#, types are inherited from the System.Type. The C# typeof operator gets the System.Type of a type. This code sample shows the use case of typeof operator using C#.
The typeof operator syntax,
System.Type type =
typeof
(type);
The following code sample uses the typeof operator to get the type of various types.
Type tp =
typeof
(
int
);
Console.WriteLine($
"typeof {tp}"
);
Console.WriteLine(
typeof
(String));
Console.WriteLine(
typeof
(Double));
The GetType() method is used to get the Type of an object or expression at runtime.
string name =
"Mahesh Chand"
;
Type namenameType = name.GetType();
Console.WriteLine(nameType);
You can also get a type of a class (object), its methods, properties, and other members.
The following code snippet returns a type of the Author object.
Console.WriteLine(
typeof
(Author));
Complete code sample,
using System;
namespace typeofOperatorSample
{
class
Program
{
static
void
Main(string[] args)
{
Type tp =
typeof
(
int
);
Console.WriteLine($
"typeof {tp}"
);
Console.WriteLine(
typeof
(String));
Console.WriteLine(
typeof
(Double));
string name =
"Mahesh Chand"
;
Type namenameType = name.GetType();
Console.WriteLine(nameType);
Console.WriteLine(
typeof
(Author));
Console.ReadKey();
}
}
public
class
Author
{
public
Author() { }
}
}
The output of the above code generates the following output.
Next > Here is an article on the
Here is an article on the Difference between the typeof Operator and GetType() 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
Use Of C# TypeOf Operator
Trusted Answers to Developer Questions
261
0
0
Comments
All Comments (0)