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 Structs
assigning value to a variable is treated as a
statement
. Again statements are also categorized in various types. Now, your question arises a confusion betweenDeclaration statements
andExpression statements
.Declaration Statements : Declaration statements are used to introduce
fields
where assignment is required for constant fields and for variable it is optional. Technically,Declaration statements
usesExpression statements
as 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 Statements
take part and technically takesExpression Statements
as part of it. But standaloneExpression Statements
as 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