GaidinD
3
Q:

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") 

//Method 3 Safe Cast Testing
YourType TheTest = YourSubject
if(TheTest != null) //or (!TheTest)
  Console.WriteLine("Is not your type you are testing for") 
else
  Console.WriteLine("Is your type you are testing for") 
2
string a = "This is a string";
Console.WriteLine(a.GetType())
1

// -------- 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!")
}
 
0

New to Communities?

Join the community