Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Use Of C# TypeOf Operator
WhatsApp
Mahesh Chand
6y
141.5k
0
13
100
Article
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.
// Get type of a variable
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.
// Get a typeof a class
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));
// Get type of a variable
string name =
"Mahesh Chand"
;
Type namenameType = name.GetType();
Console.WriteLine(nameType);
// Get a typeof a class
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
Difference between the typeof Operator and GetType() Method.
C#
TypeOf Operator
TypeOf Operator In C#
Up Next
Ebook Download
View all
DateTime in C#
Read by 1.3k people
Download Now!
Learn
View all
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.
Membership not found