-1

I am very new to C#, while studying the array in C#, I have created a small example, where I was trying to assign value to array. However, every time, the compiler gives the error:

array name doesn't exist in current context.

My code as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Calculator
{
    int sum;
    int[] EvenArray;
    List<int> evenNumbers = new List<int>();
    string[] randomNames = new string[10];

    //This line gives an complie time error, as randomNames doesn't exist in current context
    randomNames[0]="Savresh";
}
  • 4
    You can't set (an array's, but applies for all types) items outside of initialization and methods. Move the `randomNames[0]="Savresh"` inside a method, for example the `static void Main`. – nbokmans Jan 16 '18 at 15:42
  • 1
    Your code that *does things* (other than field declarations and initializers) needs to go into a *method*; btw, the compiler messages I get are CS0270 "Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)" and CS1519 "Invalid token '=' in class, struct, or interface member declaration" - nothing about not existing in the current context - that could just be different compiler versions, though – Marc Gravell Jan 16 '18 at 15:43
  • Possible duplicate of [Initialize class fields in constructor or at declaration?](https://stackoverflow.com/questions/24551/initialize-class-fields-in-constructor-or-at-declaration) – codebender Jan 16 '18 at 15:59

1 Answers1

1

You need to put it inside a method. You can't assign a value to an array without it being inside one.

private void MyMethod() {
    randomNames[0] = "Savresh";
}
a--
  • 558
  • 2
  • 15
  • is it true for all the collection classes? – user3899906 Jan 16 '18 at 15:44
  • This is true for most things that perform actions. For example, adding values to arrays, calling methods on objects etc. MUST be done inside a method. Assigning values can be done outside the method blocks though. – a-- Jan 16 '18 at 15:46
  • @user3899906 To expand: Declarations of types and variables can be done directly in the class outside any method. Such variables will be shared with all methods in the class. Such a declation may also include an assignment of an initial value. Essentially *everything else* are code statements and must be done inside a method declaration. – Oskar Berggren Jan 16 '18 at 16:59