I wanted to know why we cant do this:
public partial class Form1 : Form
{
string b;
b = "something";
public Form1()
{
InitializeComponent();
}
However I am able to do this:
public partial class Form1 : Form
{
string b = "something";
or
public partial class Form1 : Form
{
string b;
private void Form1_Load(object sender, EventArgs e)
{
b = "something";
}
I have been looking for an answer, why cant we use the first way. However I havent been able to find an answer.
In C#, a class can contain declaration of following members...
Constructors Destructors Constants Fields Methods Properties Indexers Operators Events Delegates Classes Interfaces Structsassigning value to a variable is treated as a
statement. Again statements are also categorized in various types. Now, your question arises a confusion betweenDeclaration statementsandExpression statements.Declaration Statements : Declaration statements are used to introduce
fieldswhere assignment is required for constant fields and for variable it is optional. Technically,Declaration statementsusesExpression statementsas a part of it.Expression statements : On the other hand an expression statement's responsibility is to assign value(s) to variables. But creating a variable is not it's responsibility.
So, In order to declare the Fields and constants of a class
Declaration Statementstake part and technically takesExpression Statementsas part of it. But standaloneExpression Statementsas well as other statements can only be a part of a method, property or event declaration.you can have more information about class from here and about statements from here