How do you find the Type
of a value type in C#?
Let's say i have:
string str;
int value;
double doubleValue;
Is there a method that returns the Type of any of these value types?
To be clearer, I am trying something like this:
string str = "Hello";
string typeOfValue = <call to method that returns the type of the variable `str`>
if (typeOfValue == "string") {
//do something
} else {
//raise exception
}
I want to get input from the user and raise an exception if the value entered is not a string
or int
or double
depending on my conditions.
I have tried:
public class Test
{
public static void Main(string[] args)
{
int num;
string value;
Console.WriteLine("Enter a value");
value = Console.ReadLine();
bool isNum = Int32.TryParse(value, out num);
if (isNum)
{
Console.WriteLine("Correct value entered.");
}
else
{
Console.WriteLine("Wrong value entered.");
}
Console.ReadKey();
}
}
but what if the type of value I want to check is a string
or something else?