Search code examples
c#.nettypescasting

Cast to any type


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.


Solution

  • 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"); //nullable return
    
    //nullable handling
    int num = ReadVariable<int>("int", "99") ?? default(int); //int type's default value is 0
    int num = ReadVariable<int>("int", "99").GetValueOrDefault(-1); //default to an int value of your choice
    

    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

    Update 2: added an examples of nullable handling