Home > database >  Cast to any type
Cast to any type

Time:11-11

I have a txt file where from I can extract two strings (type and value). But, I need to cast it to the correct type. See the code bellow.

string type;
string value;

//example 1 //from the txt file
type = "int";
value = "25";

//example 2
type = "double";
value = "1.3";

//example 3
type = "string";
value = "blablabla";

//conversion I would like to do:
dynamic finalResult = (type)element.Value; //this returns an error

I need to do something like this, but I don't know to create a object type from the content of the string.

I tried to declare a Type:

Type myType = type;

But I dont know how to do it correctly.

CodePudding user response:

In the name of clarity and type safety I think you should just use a combination of a switch expression and the various .TryParse() methods, having it return a generic type

static T ReadVariable<T>(string type, string value) =>
    type switch  
    {  
        "int" => int.TryParse(value, out int val) ? val : null, //null or throw an ex
        "double" => double.TryParse(value, out double val) ? val : null,
        "string" => string.TryParse(value, out string val) ? val : null,
        "bool" => bool.TryParse(value, out bool val) ? val : null,
        //... etc
        _ => throw new NotSupportedException("This type is currently not supported")
    };

int num = ReadVariable<int>("int", "99");

Are you really going to have a situation where you need to parse out any type under the sun? This method allows you to maintain full control over what happens. Use of dynamic may potentially be way more headache than you expect

Update: thanks to @ckuri for pointing out that you may also want to use the try parse overload that allows for invariant culture in order to account for international numbering schemes

CodePudding user response:

does this work?

object result;
string value = "some value";
string type = "some type";
switch(type)
{
   case "int":
      result = Convert.ToInt32(value);
      break;
   case "double":
      result = Convert.ToDouble(value);
      break;
   case "string":
      result = value;
      break;
   // case "any other datatype":
   //    result = convert explicitly to that datatype
}

CodePudding user response:

You can use Convert.ChangeType(element.Value, type).

Convert.ChangeType Method

dynamic finalResult = Convert.ChangeType(element.Value, type);

but you would need to resolve an actual type, not a string.

  • Related