Search code examples
c#runtimemathnet-numerics

C# decide between complex or standard double type during runtime


I'm writing a sci-comp application in C# (not to be confused with comp-sci), which should accept user inputs as both real and complex numbers. This difference between possible inputs would ideally reflect in many points down the stream - if inputs are simple real numbers, I want all objects created from there onwards as simple doubles; if inputs have complex numbers, all relevant objects necessarily must be of complex numbers. (Their syntax, methods and overloads are identical)

Now, the reason why I want to do this is that, although it would be safer to assume all inputs as complex from early on, I can save on memory (and potentially processing time) if I can use double types when appropriate. I see that would consume only half the necessary memory, and arithmetic operations are simpler in these cases.

To put this simply, during run-time my code would decide what's more appropriate depending on user input, which is acceptable given that syntax is fully re-usable. I will try to outline an example using simple int and double datatypes to make this more clear:

    Console.WriteLine("Enter input: ");
    var input = Console.ReadLine();

    bool hasValuesAfterComma = isInputFractional(input);

    double myVar = Double.Parse(input); // This is executed if hasValuesAfterComma == true,
    int myVar = Int.Parse(input); // Otherwise this is considered. All statements after this line work both with double or int types.

How can I set the appropriate data type during runtime?

P.S. I'm using the MathNet.Numerics package and its data types to do Linear Algebra processing.


Solution

  • Try dynamic variable:

    dynamic myVar = hasValuesAfterComma? Double.Parse(input): Int.Parse(input);