I define this variables in my code, I want to initialize them in one step, how can I do this?
int currentYearSavingDays, currentYearSavingXMins, currentYearSavingNXMins, currentYearUsedDays, currentYearUsedXMins, yearLimitRemainingDays, yearLimitRemainingXMins, totalYearlyDays, totalYearlyXMins, totalSavingDays, totalSavingMins, totalUsableDays, totalUsableMins, nextYearTotalUsableDays, nextYearTotalUsableMins, dayWorkMinutes, previousYearRemainingDays, previousYearRemainingMins;
forExample:
currentYearSavingDays, currentYearSavingXMins, currentYearSavingNXMins, currentYearUsedDays, currentYearUsedXMins, yearLimitRemainingDays, yearLimitRemainingXMins, totalYearlyDays, totalYearlyXMins, totalSavingDays, totalSavingMins, totalUsableDays, totalUsableMins, nextYearTotalUsableDays, nextYearTotalUsableMins, dayWorkMinutes, previousYearRemainingDays, previousYearRemainingMins = 0;
The best I know is this.
int currentYearSavingDays, currentYearSavingXMins, currentYearSavingNXMins, currentYearUsedDays, currentYearUsedXMins, yearLimitRemainingDays, yearLimitRemainingXMins, totalYearlyDays, totalYearlyXMins, totalSavingDays, totalSavingMins, totalUsableDays, totalUsableMins, nextYearTotalUsableDays, nextYearTotalUsableMins, dayWorkMinutes, previousYearRemainingDays, previousYearRemainingMins;
currentYearSavingDays = currentYearSavingXMins = currentYearSavingNXMins = currentYearUsedDays = currentYearUsedXMins = yearLimitRemainingDays = yearLimitRemainingXMins = totalYearlyDays = totalYearlyXMins = totalSavingDays = totalSavingMins = totalUsableDays = totalUsableMins = nextYearTotalUsableDays = nextYearTotalUsableMins = dayWorkMinutes = previousYearRemainingDays = previousYearRemainingMins = 0;
I would frown upon the attempt to declare them all at once. In addition to being ugly to read, it is not necessary.
Instead, this seems like a great candidate for a set of fields for a class or struct.
In C#, value type fields are allocated and automatically initialized to their default value by the memory manager. So, in this particular case, if you had created a new class/struct for just these values, then you wouldn't have to explicitly initialize them.
Note that you could simply leave them as fields in the current class as well, so long as you're careful not to violate the single responsibility principle.
Also note that the strategy described in this answer will not work if these are local variables. As this answer explains, while the initialization semantics are the same, use of uninitialized local variables is generally a bug and is not allowed in C#. In that case, it would be better, in my opinion, to declare and initialize each variable on its own line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With