Search code examples
c#.netvariablestype-inferencedynamic-typing

Reassigning weakly typed variable casting


Given that in C# we can have the weak type var which can be of any type until it's set, is it possible to have the same var change type depending on the output of a test?

For example

var c = DBQuery.FindString("paramater", "data");

this will return NULL if the query is unsuccessful or a string if it works.

From what I can see, as FindString is has a return type of string, var c is typed as a string, despite it being null.

Is there a way to unset the typing of c so that it can then be used for

var c = DBQuery.FindInt("parameter", "data2");

Thanks


Solution

  • The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

    The keyword you are probably looking for is dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation.

    Given this example

    dynamic c = "foo";
    Console.WriteLine(test.GetType());
    
    c = 2;
    Console.WriteLine(test.GetType());
    

    Output

    System.String
    System.Int32

    Nevertheless, I suggest you to adapt your code to avoid the dynamic type, mainly because you lose the ability to detect error at compile-time and the ability to use IntelliSense.

    Additional resources

    The var keyword: http://msdn.microsoft.com/en-us/library/bb384061.aspx
    The dynamic keyword: http://msdn.microsoft.com/en-us/library/dd264736.aspx