C# .NET - What is wrong with this code? - Asked By balaji on 17-Aug-12 07:14 AM

class demo
{
  string str="";
  str="balaji";  //here i'm not able to assign value.why.?
 
}
Peter Bromberg replied to balaji on 17-Aug-12 08:03 AM
class Demo
{
  public string Str {get;set;}
 
public Demo ()
{
Str="balaji";  
}
 
}

balaji replied to Peter Bromberg on 17-Aug-12 08:12 AM
pls ans for why i can't? i don't want alternative.
Tom Wilson replied to balaji on 17-Aug-12 08:50 AM
To assign the value, it must be in a method, not the class level.
Robbe Morris replied to balaji on 17-Aug-12 11:16 AM
You are attempting to execute code that is outside of a property get/set, event handler, or method.

You can do this outside these blocks because you are declaring a class level variable

  string Str = "stuff";

This is not declaring a variable.  It is attempting to execute code outside of the three code block types mentioned above.

  Str = "stuff";

The following is an example of executing code in a method.

private void DoStuff()
{
   Str = "stuff";
}
balaji replied to Robbe Morris on 18-Aug-12 07:43 AM
Thank you very much