get object type C# code example

Example 1: c# get type of object

//Exact runtime type of the current instance.
object.GetType();

Example 2: get type of variable c#

string a = "This is a string";
Console.WriteLine(a.GetType())

Example 3: c# find the type of a variable

// -------- HOW TO FIND IF A VARIABLE IS OF A CERTAIN TYPE? ---------//
// You can use the keywords: "is" and "as"

// .....1º Method..... //
using System.Text

ArrayList myArray = new ArrayList();   // Class ArrayList. It creates a mutable array of objects of different types

myArray.Add("Hello");
myArray.Add(12);
myArray.Add('+');
myArray.Add(10);
		
int myVariable = 0;
		
foreach(object obj in myArray){     // You can use "var" instead of "object" 
			
	if(obj is int)                          // You use the "is" keyword
		myVariable += Convert.ToInt32(obj); // You need to convert the variable objet to what it contains for the compiler to accept this operation  
  
	if(obj is string)
		Console.WriteLine(obj + " World");
}
			
Console.WriteLine(myVariable);



// .....2º Method.... //

Cube myTest = myVariable as Cube;   // Where Cube is a class named "Cube" and I want to know if myVariable is of type Cube 

if(myTest == null){
  Console.WriteLine("MyVariable it's not a Cube!") 
}
else {
   Console.WriteLine("MyVariable is a Cube!")
}

Example 4: c# get type of class

Type tp = value.GetType();

Example 5: how to find the type of a object c#

use the "is" keyword