csharp how to initialize an array

Code Example - csharp how to initialize an array

                
                        var array = new int[] { 1, 2, 3 }
var array2 = new ObjectName[] { /* add element to array here */ };
                    
                
 

csharp initialize array

                        
                                string[] stringArray = new string[6];
//or
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
//
string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
//etc
                            
                        
 

csharp create array

                        
                                // Define and Initialize
int[] arr = {1, 2, 3};

// Buuuut:
// Initial defining
int[] arr;

// This works
arr = new int[] {1, 2, 3};   

// This will cause an error
// arr = {1, 2, 3};
                            
                        
 

csharp int array initial values

                        
                                When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.
                            
                        
 

csharp define array

                        
                                float[] floats = new float[]{1.0,1.1,1.4,1.23,2212.233};
                            
                        
 

array declaration in csharp

                        
                                // Syntax: data_type[] variable_name = new data_type[size];

// Decalring array of integers of length 5
int[] intArr = new int[5];

// Declaring array of strings of length 5
string[] names = new string[5];

// We can also populate the array, if we know the elements in advance
int[] evenDigits = new int[] {0,2,4,6,8}; // notice that in this, we don't need explicit size declaration.
                            
                        
 

csharp initialize array of objects

                        
                                Object[] objArray = new Object[] {new Object(), ... , new Object()};