c3 method check types code example
Example: 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!")
}