-1

For below code, the "GetType()" is same (String) for Var result & result1.

var result = "abc";
        var result1 = "10.17";

        string a = result.GetType().Name;
        string b = result1.GetType().Name;

How to get actual data type for above variables?

user584018
  • 10,186
  • 15
  • 74
  • 160
  • 3
    Because result1 is also a string having number in it. It type is not numeric. – Adil Apr 06 '17 at 10:48
  • 2
    Actual data type for both is indeed `string`, and you got it. @ThePerplexedOne `typeof(result)` won't even compile. – Evk Apr 06 '17 at 10:49
  • If youre in the debugger. Hover oflver the var keyword and it will tell you what the type is. – Chris Watts Apr 06 '17 at 10:49
  • I brainfarted with my previous comment. Check this for information regarding type checking: http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is – ThePerplexedOne Apr 06 '17 at 10:51

3 Answers3

0

By "actual data type" you, probably, mean "can the data be treated (converted) as double, int" etc. If it's your case, try using TryParse, possible C# 7.0 (out var construction) implementation:

    var result1 = "10.17";

    if (int.TryParse(result, out var intValue)) {
      // result1 can be treated as int - intValue
    }
    else if (double.TryParse(result, 
                             NumberStyles.Any, 
                             CultureInfo.InvariantCulture, 
                             out var doubleValue)) {
      // result1 can be treated as double - doubleValue
    }
    else {
      // result1 is a string which can't be converted to int, double 
    } 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Variables declare using var are implicitly typed variables but are (different to using dynamic) strongly typed. So the variable you use will have the type of the value you assign to it and it is not possible to assign values of another type.

string a = "foobar";
var b = "foobar";
int c = 10;
var d = 10;

a and b will both be of type string. Because b gets a string assigned. So are c and d both of type int.

This will generate a compiler error

var a = "foobar";
var i = 10;
a = i;

Because you can't assign an int to a variable of type string.

For more information on var take a look at the var (C# reference).

MiGro
  • 471
  • 1
  • 4
  • 17
0
string a ="12.22";
int result;

double result1;
string ans = string.Empty;

if(int.TryParse(a,out result))
{
  ans = "Integer";
}
else if(double.TryParse(a,out  result1))
{
  ans = "double";
}
else
{
  ans = "string";
}
Radu Diță
  • 13,476
  • 2
  • 30
  • 34
Arpit Shah
  • 37
  • 1
  • 9
  • read this and format your code : https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks – isuruAb Apr 06 '17 at 11:25
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – ryanyuyu Apr 06 '17 at 14:10