Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# doubt, finding the datatype

Tags:

c#

types

parsing

I have the following variables:

string str1 = "1";
string str2 = "asd";
string str3 = "3.5";
string str4 = "a";

Now I need to find the data type of each string i.e. the data type to which it can be converted if quotes are removed. Here is what I would like each variable to convert to:

str1 - integer
str2 - string
str3 - double
str4 - char

Note: if the string has single character it should be char, though a string can have single letter, I'm limiting it.

FYI: these values are obtained from DataGrid where i manually entered values. So everything is becoming a string. Is there any way to do this?

like image 908
SyncMaster Avatar asked Apr 07 '26 19:04

SyncMaster


2 Answers

Of course, there's no definite way to do this, but if you create a list of data types you want to check ordered by priority, then something like this may do the trick.

object ParseString(string str)
{
    int intValue;
    double doubleValue;
    char charValue;
    bool boolValue;

    // Place checks higher if if-else statement to give higher priority to type.
    if (int.TryParse(str, out intValue))
        return intValue;
    else if (double.TryParse(str, out doubleValue))
        return doubleValue;
    else if (char.TryParse(str, out charValue))
        return charValue;
    else if (bool.TryParse(str, out boolValue))
        return boolValue;

    return null;
}

Just call this function on each string, and you should have the appropiate type of object returned. A simple type check can then tell you how the string was parsed.

like image 114
Noldorin Avatar answered Apr 09 '26 09:04

Noldorin


Use meta-data, if you can

That you have to guess what the data types are, is not a good idea.

Two things

1 Where is the data coming from?

If it's a database, are you sure they're strings? If it is a database, there should be some meta data returned that will tell you what the datatypes of the fields are.

If it's an Xml file, is there a schema defined that will give you the types?

2 If you have to continue to guess.

Be aware that you can have strings that happen to be numbers, but are perfectly valid strings e.g phone numbers, bank acount numbers, that are best expressed as strings. Also these numbers can have many digits, if you convert them to doubles you may loose some digits to floating point inaccuracies (you should be OK up to 14 or 15 digits)

I'm sure by now - cause I've taken my time typing this - there are lots of answers telling you how to do this (i.e. tryparse int first, then double, then test length for char, if not then it's a string etc), but if I were you, I'd try to NOT do that, and see if there's any way you can get, or pass some meta-data that will tell you what type it IS and not just what type it might be

like image 28
Binary Worrier Avatar answered Apr 09 '26 07:04

Binary Worrier