-1

These simple two line code giving me error A field initializer cannot reference the nonstatic field, method, or propertyClassName.value'` . i just follow tutorial from enter link description here. I am using this code in unity3d.

// Input string.

string value = "Dot Net Perls";

// Use ToCharArray to convert string to array.

char[] array = value.ToCharArray();
Community
  • 1
  • 1
Pawan Chaurasiya
  • 881
  • 2
  • 16
  • 30

1 Answers1

1

I guess you are trying to access value in the class scope like this:

class Foo
{  
   string value = "Dot Net Perls"; 
   char[] array = value.ToCharArray();
}

This is not allowed. You can only declare class members in the class scope, other statements that includes instance members should be written inside of a method.Even the initalization at this scope is just a syntactic sugar. When you do:

string value = "Dot Net Perls"; 

Compiler will move the initalization to the constructor.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • 1
    *other statements should be written inside of a method* That's not true. If you mark both the fields as `static` it will work without any problem. – Sriram Sakthivel Dec 30 '14 at 10:24