简体   繁体   中英

Type inference rules in C#?

I read the following MSDN page, which states the following interesting thing:

The first rule is that the var declaration follows the normal type inference rules: The type is inferred to be the static type of the switch expression. From that rule, the type always matches.

Nowhere in MSDN could I find a reference to the so-called "normal type inference rules", and why does var used in that sense infer to the static type of the switch expression?

Perhaps I don't know what a static type is. I know what the static keyword does, but I don't think that's what's happening in the switch expression.

C# is a statically typed language, meaning that types must be known at compile-time, and the type assigned to a variable cannot change at runtime. Consider first that all of the following lines result in exactly the same thing:

int x = 123;
System.Int32 x = 123;
var x = 123;
  • int is just an alias for System.Int32
  • The compiler infers that x is of type System.Int32 when using var because it's been assigned an integral number.

What you can't do with C# that you can do in dynamically typed languages (like javaScript) is this:

var x = 123;
x = "Hello world";

In C# the compiler will complain that you cannot assign a string to an int variable, but JavaScript, being a dynamic language will allow it.

Perhaps I don't know what a static type is. I know what the static keyword does, but I don't think that's what's happening in the switch expression.

In the example that you have linked, by " static type of the switch expression " they are referring to the type of the variable shapeDescription - eg type string .

In other words, following " normal type inference rules " - the var o also has type string .

static object CreateShape(string shapeDescription)
{
    switch (shapeDescription)
    {
        // removed for conciness

        case var o when (o?.Trim().Length ?? 0) == 0:
            // white space
            return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM