0

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?

samy
  • 14,832
  • 2
  • 54
  • 82
Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
  • `Object.GetType`?! But it's not clear, the user can enter only strings. So the type is always string. If you parse it to a number type you know already the type at compile time. – Tim Schmelter Oct 16 '14 at 13:07
  • 3
    Just a side note, `string` is not a value type – Habib Oct 16 '14 at 13:08
  • 2
    I'm not seeing *why* you need this here. This could be useful if you had an `Object`, but a string read from the console is a string and nothing else unless you parse it, then the parse result is a known type at that point. – crashmstr Oct 16 '14 at 13:08

2 Answers2

2

You can use GetType on any element in .Net since it exists at the object level :

var myStringType = "string".GetType();
myStringType == typeof(string) // true

GetType returns a Type object, you can get a readable human friendly name by using the Name property on the Type.

samy
  • 14,832
  • 2
  • 54
  • 82
0

GetType will return the correct result:

string typeOfValue = value.GetType().ToString();

But in this instance, you do not need to convert the type to a string for the comparison:

if (typeof(String) == value.GetType()) ...
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114