c# get type of class
Type tp = value.GetType();
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!")
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us