C# Keywords Tutorial Part 87: typeof
Object-oriented programmers all across the world utilize the well-liked language C#. The typeof keyword, which is used to acquire the System, is only one of the numerous aspects of C#.item of a specific kind. We will examine the typeof keyword and its use using code samples in this blog article.
The Type object, which represents a type, may be obtained in C# using the typeof keyword. This Type object includes information on the type’s name, methods, and attributes. When you need to carry out operations dependent on the type of an object during runtime, this is helpful.
Here is an example that shows the usage of the typeof
keyword:
using System; class Program { static void Main(string[] args) { Type intType = typeof(int); Console.WriteLine(intType.FullName); // Output: System.Int32 } }
In the above example, we have obtained the Type
object of the int
type using the typeof
keyword. We then printed the full name of the int
type using the FullName
property of the Type
object.
Another usage of the typeof
keyword is when you want to check if an object is of a certain type. Here is an example that demonstrates this:
using System; class Program { static void Main(string[] args) { object myObj = 10; if (myObj.GetType() == typeof(int)) { Console.WriteLine("myObj is of type int."); } } }
In the above example, we have created an object myObj
that contains the value 10
. We then used the GetType
method of the object to obtain its Type
object. We then checked if the Type
object of myObj
is equal to the Type
object of the int
type obtained using the typeof
keyword. If the Type
objects are equal, we print a message to the console.
One important thing to note about the typeof
keyword is that it can only be used with types that are known at compile-time. This means that you cannot use the typeof
keyword with a variable or an expression that evaluates to a type at runtime.
Leave a Reply