Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-initializing C# lists

I am creating a new C# List (List<double>). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0?

like image 348
JasCav Avatar asked Jul 09 '09 15:07

JasCav


People also ask

What is automatic variable initialization C?

Automatic variables are variables defined inside a function or block of code without the static keyword. These variables have undefined values if you don't explicitly initialize them. If you don't initialize an automatic variable, you must make sure you assign to it before using the value.

What do you mean by auto initialization?

Automatic initialization in JavaJava does not initialize non-array local variables (also referred to as automatic variables) . The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.

Are auto variables initialized to zero in C?

Example# In the absence of explicit initialization, external and static variables are guaranteed to be initialized to zero; automatic variables (including register variables) have indeterminate1 (i.e., garbage) initial values.

How do you initialize an auto variable?

You can initialize any auto variable except function parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression.


1 Answers

In addition to the functional solutions provided (using the static methods on the Enumerable class), you can pass an array of doubles in the constructor.

var tenDoubles = new List<double>(new double[10]); 

This works because the default value of an double is already 0, and probably performs slightly better.

like image 157
Michael Meadows Avatar answered Oct 18 '22 00:10

Michael Meadows