Declare and assign multiple string variables at the same time

前端 未结 10 2273
醉话见心
醉话见心 2020-12-08 13:03

I\'m declaring some strings that are empty, so it won\'t throw errors later on.

I\'ve read that this was the proper way:

string Camnr = Klantnr = Ord         


        
相关标签:
10条回答
  • 2020-12-08 13:23

    Try with:

     string Camnr, Klantnr, Ordernr, Bonnr, Volgnr, Omschrijving;
     Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = string.Empty;
    
    0 讨论(0)
  • 2020-12-08 13:24

    You can to do it this way:

    string Camnr = "", Klantnr = "", ... // or String.Empty
    

    Or you could declare them all first and then in the next line use your way.

    0 讨论(0)
  • 2020-12-08 13:27

    Just a reminder: Implicit type var in multiple declaration is not allowed. There might be the following compilation errors.

    var Foo = 0, Bar = 0;
    

    Implicitly-typed variables cannot have multiple declarators

    Similarly,

    var Foo, Bar;
    

    Implicitly-typed variables must be initialized

    0 讨论(0)
  • 2020-12-08 13:28

    All the information is in the existing answers, but I personally wished for a concise summary, so here's an attempt at it; the commands use int variables for brevity, but they apply analogously to any type, including string.

    To declare multiple variables and:

    • either: initialize them each:
    int i = 0, j = 1; // declare and initialize each; `var` is NOT supported as of C# 8.0
    
    • or: initialize them all to the same value:
    int i, j;    // *declare* first (`var` is NOT supported)
    i = j = 42;  // then *initialize* 
    
    // Single-statement alternative that is perhaps visually less obvious:
    // Initialize the first variable with the desired value, then use 
    // the first variable to initialize the remaining ones.
    int i = 42, j = i, k = i;
    

    What doesn't work:

    • You cannot use var in the above statements, because var only works with (a) a declaration that has an initialization value (from which the type can be inferred), and (b), as of C# 8.0, if that declaration is the only one in the statement (otherwise you'll get compilation error error CS0819: Implicitly-typed variables cannot have multiple declarators).

    • Placing an initialization value only after the last variable in a multiple-declarations statement initializes the last variable only:

      int i, j = 1;// initializes *only* j

    0 讨论(0)
提交回复
热议问题