141

How can I find out what data type some variable is holding? (e.g. int, string, char, etc.)

I have something like this now:

private static void Main()
{
   var someone = new Person();
   Console.WriteLine(someone.Name.typeOf());
}

public class Person
{
    public int Name { get; set; }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Limeni
  • 4,954
  • 8
  • 31
  • 33
  • 7
    You've already defined the type - `int` – Jamiec Jul 24 '12 at 15:23
  • This is unclear what you mean by "find out the data type". Normally, the answer is "you just look at the class member signature and the type is stated there in an explicit way". Is your intention to inspect class members in the run time? – Wiktor Zychla Jul 24 '12 at 15:25
  • 1
    Out of subject, but what you wrote here is better written like this with C# : `class Person { public string Name { get; set; } }` or `class Person { private string m_Name; public string Name { get {return m_Name;} set { m_Name = value; } }`. Read the documentation about [Properties](http://msdn.microsoft.com/en-us/library/w86s7x04.aspx) – Steve B Jul 24 '12 at 15:26
  • 1
    Jamiec is right. Static typing means the declaration sets your type forever. Your variable n can only be of the type you declared, or an inherited type. In your specific case you chose to display an int, that's a type you can't inherit from, so n can only be an int. – Ksempac Jul 24 '12 at 15:27

9 Answers9

189

Other answers offer good help with this question, but there is an important and subtle issue that none of them addresses directly. There are two ways of considering type in C#: static type and run-time type.

Static type is the type of a variable in your source code. It is therefore a compile-time concept. This is the type that you see in a tooltip when you hover over a variable or property in your development environment.

Run-time type is the type of an object in memory. It is therefore a run-time concept. This is the type returned by the GetType() method.

An object's run-time type is frequently different from the static type of the variable, property, or method that holds or returns it. For example, you can have code like this:

object o = "Some string";

The static type of the variable is object, but at run time, the type of the variable's referent is string. Therefore, the next line will print "System.String" to the console:

Console.WriteLine(o.GetType()); // prints System.String

But, if you hover over the variable o in your development environment, you'll see the type System.Object (or the equivalent object keyword).

For value-type variables, such as int, double, System.Guid, you know that the run-time type will always be the same as the static type, because value types cannot serve as the base class for another type; the value type is guaranteed to be the most-derived type in its inheritance chain. This is also true for sealed reference types: if the static type is a sealed reference type, the run-time value must either be an instance of that type or null.

Conversely, if the static type of the variable is an abstract type, then it is guaranteed that the static type and the runtime type will be different.

To illustrate that in code:

// int is a value type
int i = 0;
// Prints True for any value of i
Console.WriteLine(i.GetType() == typeof(int));

// string is a sealed reference type
string s = "Foo";
// Prints True for any value of s
Console.WriteLine(s == null || s.GetType() == typeof(string));

// object is an unsealed reference type
object o = new FileInfo("C:\\f.txt");
// Prints False, but could be true for some values of o
Console.WriteLine(o == null || o.GetType() == typeof(object));

// FileSystemInfo is an abstract type
FileSystemInfo fsi = new DirectoryInfo("C:\\");
// Prints False for all non-null values of fsi
Console.WriteLine(fsi == null || fsi.GetType() == typeof(FileSystemInfo));

Another user edited this answer to incorporate a function that appears below in the comments, a generic helper method to use type inference to get a reference to a variable's static type at run time, thanks to typeof:

Type GetStaticType<T>(T x) => typeof(T);

You can use this function in the example above:

Console.WriteLine(GetStaticType(o)); // prints System.Object

But this function is of limited utility unless you want to protect yourself against refactoring. When you are writing the call to GetStaticType, you already know that o's static type is object. You might as well write

Console.WriteLine(typeof(object)); // also prints System.Object!

This reminds me of some code I encountered when I started my current job, something like

SomeMethod("".GetType().Name);

instead of

SomeMethod("String");
phoog
  • 42,068
  • 6
  • 79
  • 117
  • 3
    so `variable.getType()` returns the runtime type(the right hand side type), but what returns the static type(the left hand side type of a variable)? – barlop Dec 24 '15 at 12:21
  • @barlop that is known at compile time. You can use `typeof` to get a type object at runtime for the static type. – phoog Dec 24 '15 at 16:19
  • yes I know static type = compile time type, and runtime type=dynamic type. Though re getting the type of variable 'a', you can't do `typeof(a)` if you do `typeof(int)` it will return int, but isn't checking the variable 'a' and showing you the type of 'a'.. You could say that you don't need to show the static type of 'a', that may be so, but the fact is that it isn't showing it. So I don't see how the use of typeof here is useful. – barlop Dec 24 '15 at 18:34
  • @barlop To go back one step, how is knowing the static type at runtime useful? – phoog Dec 24 '15 at 18:55
  • 6
    @barlop you could do this to let type inference take care of it for you: `Type GetStaticType < T > (T x) { return typeof(T); }` – phoog Dec 24 '15 at 19:35
  • could you use `switch (variable.GetType())` and then `case typeof(bool): ...` ?? – Jaquarh Apr 14 '16 at 13:44
  • @KyleE4K You can only switch on a numeric integer type or a string. – phoog Apr 14 '16 at 15:50
  • Its okay, I switched like 50 lines of coding with like 6 lines of SQL ;) Thanks though! @phoog – Jaquarh Apr 14 '16 at 16:02
  • 1
    @Jaquarh as you may have noticed, `switch` now supports pattern matching for type testing (of runtime type, not static). Instead of switching on the value returned from GetType(), you switch on the variable directly. – phoog Oct 06 '19 at 15:24
25

Its Very simple

variable.GetType().Name

it will return your datatype of your variable

Sagar Chavan
  • 507
  • 1
  • 7
  • 15
  • 2
    This isn't correct: `object o = "Hi!"; return o.GetType().Name;` returns `"String"`, not `"Object"`. – phoog Aug 14 '21 at 20:22
17

Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:

If you know the type you want to compare it with, use the is or as operators:

if( unknownObject is TypeIKnow ) { // run code here

The as operator performs a cast that returns null if it fails rather than an exception:

TypeIKnow typed = unknownObject as TypeIKnow;

If you don't know the type and just want runtime type information, use the .GetType() method:

Type typeInformation = unknownObject.GetType();

In newer versions of C#, you can use the is operator to declare a variable without needing to use as:

if( unknownObject is TypeIKnow knownObject ) {
    knownObject.SomeMember();
}

Previously you would have to do this:

TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
    knownObject.SomeMember();
}
Dai
  • 141,631
  • 28
  • 261
  • 374
4

Use the GetType() method

http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx

Stephen Oberauer
  • 5,237
  • 6
  • 53
  • 75
4

Just hold cursor over member you interested in, and see tooltip - it will show memeber's type:

enter image description here

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
3

One option would be to use a helper extension method like follows:

public static class MyExtensions
{
    public static System.Type Type<T>(this T v) => typeof(T);
}

var i = 0;
console.WriteLine(i.Type().FullName);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Acerby
  • 31
  • 1
1

GetType() method

int n = 34;
Console.WriteLine(n.GetType());
string name = "Smome";
Console.WriteLine(name.GetType());
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Shyju
  • 214,206
  • 104
  • 411
  • 497
1

Use the Object.GetType Method, this will do the job.

If you just wanna know the type of a variable:

var test = (byte)1;
Console.WriteLine(test.GetType());
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
0

Check out one of the simple way to do this

// Read string from console

string line = Console.ReadLine(); 
int valueInt;
float valueFloat;

if (int.TryParse(line, out valueInt)) // Try to parse the string as an integer
    Console.Write("This input is of type Integer.");
else if (float.TryParse(line, out valueFloat)) 
    Console.Write("This input is of type Float.");
else
    Console.WriteLine("This input is of type string.");
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Kiran Solkar
  • 1,204
  • 4
  • 16
  • 29