How do you determine the type of a variable in C#? code example
Example 1: find type of variable c#
//Method 1 Getting the framework type info
string StringType
Type TheType = StringType.GetType();
//Then TheTypeVariable will have all the information on the type
Console.WriteLine(TheType.Name)
//Using System.Reflection you can also find all the properties ee my answer on
//Method 2 Testing
if(YourVar is YourType)
Console.WriteLine("Is your type you are testing for")
Example 2: 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!")
}