Declare and assign multiple string variables at the same time
Asked Answered
P

11

99

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 = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";

But that doesn't work. I get this error: Klantnr does not exist in the current context.

What did I do wrong?

Pallaton answered 14/11, 2012 at 7:13 Comment(1)
Because i want to declare the variables at the start, and define them on the fly later (depends on the given input)Pallaton
E
186

You can do it like:

string Camnr, Klantnr, Ordernr, Bonnr, Volgnr;// and so on.
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = string.Empty;

First you have to define the variables and then you can use them.

Extortioner answered 14/11, 2012 at 7:16 Comment(4)
@Extortioner can we do same for session and viewbag? Like: Session["a"] = ViewBag.aa = "hello";Favata
@Dhwani, not sure, why don't you try itExtortioner
Note that this will assign all of the values to the same reference. So for instance, if you are assigning all of the variables to the same list, it will add to all collections. Tested in .NET Framework using object.ReferenceEquals.Reversioner
@ellison, yes , but just how strings are immutable, any change in any specific variable will not have an impact on others.Extortioner
P
71

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.

Pibgorn answered 14/11, 2012 at 7:15 Comment(4)
You should use String.Empty (String.Empty creates no object so it is more efficient than "", also readability is better)Forepaw
@plurby, string.Empty is same as using "". See #263691Extortioner
"" will be created once per assembly or once per AppDomain (the performance is insignificant but i wanted to point to the approach that's more readable).Forepaw
@plurby I already added that option as a comment. However, performancewise you most probably wouldn't ever notice any difference, and some people also find "" easier to read. I'd say that makes it a matter of personal (or team) preference, so i used the same as in the question.Pibgorn
E
11

An example of what I call Concatenated-declarations:

string Camnr = "",
        Klantnr = "",
        Ordernr = "",
        Bonnr = "",
        Volgnr = "",
        Omschrijving = "",
        Startdatum = "",
        Bonprioriteit = "",
        Matsoort = "",
        Dikte = "",
        Draaibaarheid = "",
        Draaiomschrijving = "",
        Orderleverdatum = "",
        Regeltaakkode = "",
        Gebruiksvoorkeur = "",
        Regelcamprog = "",
        Regeltijd = "",
        Orderrelease = "";

Just my 2 cents, hope it helps someone somewhere.

Electroscope answered 10/10, 2014 at 14:23 Comment(2)
I appreciate your 2 cents. But it seems like your answer is the same as that of botz3000 (only u use indentation)Pallaton
Ah, I saw now. You are right, this is the same, except this actually has decent formatting included.Electroscope
M
6

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 with separate values:
int i = 0, j = 1; // declare and initialize each, single-type only.
// Note: `var` is NOT supported as of C# 8.0, but see below.

// ===
// C#  7.0+ / .NET Framework 4.7+ using syntactic sugar based on *value tuples*:

// Infer the types from the RHS tuple elements.
var (i, s) = (0, "hi");

// Explicitly type the individual variables.
(int i, string s) = (0, "hi");
  • or: initialize them all with 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:

  • Unless you use the value-tuple syntax, 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

Milissamilissent answered 4/2, 2020 at 3:5 Comment(0)
W
6

One can declare and initialize multiple variables in the following way nowadays:

var (anInt, aFloat, aBoolean, aChar, aString, anArray, aRecordType, anObjectType) = 
    (1, 2.14, true, 'a', "C# is awesome!", new[] { "Asia", "Europe" } , new Country { Name = "India"}, new City { Name = "Kolkata"} ); 
Console.WriteLine(anInt);
Console.WriteLine(aFloat);
Console.WriteLine(aBoolean);
Console.WriteLine(aChar);
Console.WriteLine(aString);
Array.ForEach(anArray, Console.WriteLine);
Console.WriteLine(aRecordType.Name);
Console.WriteLine(anObjectType.Name);

Following are the definition of required custom types:

internal record Country { internal string Name {get; set;}}
internal class City { internal string Name {get; set;}}

This has been tested on .NET 5/C# 9.

Following is the output in Linqpad:

Weighting answered 13/5, 2021 at 9:57 Comment(0)
A
5

Try with:

 string Camnr, Klantnr, Ordernr, Bonnr, Volgnr, Omschrijving;
 Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = string.Empty;
Anthropophagy answered 14/11, 2012 at 7:16 Comment(0)
M
5

Try

string     Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum ,    Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease ;

and then

Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";
Montford answered 14/11, 2012 at 7:19 Comment(0)
W
4
string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease;
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = string.Empty;
Whiteley answered 14/11, 2012 at 7:22 Comment(0)
S
4

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

Sulphur answered 12/7, 2018 at 21:31 Comment(0)
A
3

string a = "", b = a , c = a, d = a, e = a, f =a;

Allegro answered 31/1, 2020 at 11:31 Comment(1)
Please add some explanation to your answer.Coition
S
0

Fairly old question but incase someone goes back.
This isn't as compact as the other answers above, but fairly readable and easier to type using Visual Studio Multi-Line selection shortcut [Alt+ Shift + ↑] (or other directions)

string Camnr = string.Empty;
string Klantnr = string.Empty;

Type out all variable names on new lines. Multi-Select in front of them an type "string". Multi-Select behind them and type "= string.Empty;".

Segment answered 17/11, 2017 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.