Declaring and Initialising variables

237 views Asked by At

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.

4

There are 4 answers

0
PaulShovan On

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 between Declaration statements and Expression 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 uses Expression 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 takes Expression Statements as part of it. But standalone Expression 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

0
Mason Howard On

This statement:

string b;

is an initialization statement. Only initialization and declarations / definitions are allowed in a class body.

This statement:

b = "something";

is an assignment statement, a type of expression. It actually "returns" something, b.

This statement:

string b = "something";

This is also an initialization statement. The reason you can write this one, but not the assignment statement, is because the formal language of c# doesn't let you. I haven't seen the formal language definition, but I imagine it looks something like this

InitializationStatement => TypeExpression Symbol  {AssignmentExpressionStatement | ';'}
AssignmentExpressionStatement => '=' EvaluatableExpression ';'

The curly braces mean what's inside is optional, and the pipe means or. This is what makes the language a language the compiler can understand. The more flexible these rules, the more difficult to make a compiler for it, the more difficult to make development software for it, the more confusing the code.


TLDR: You can't put them in for the same reason you can't put 2+2 in a class declaration.

0
atlaste On

I have been looking for an answer, why cant we use the first way.

Well, basically because the C# team decided it's not a good idea to do it like that, or because they never had this idea in the first place.

But let's go with it for a second:

You can of course make it a feature request. At that point, they will balance the pro's and the cons. Let's do that, and consider the following piece of code:

public class Foo
{
    int x = 12;
    int y;
    y = 12 + MyMethod();

    public Foo()
    {
        y = MyMethod();
    }

    public int MyMethod() 
    { 
       //***
       return x + 1;
    }
}

Now, the constructor Foo will be called when Foo is initialized. So, what value will y have after the initialization? And how many times will we call MyMethod? What will happen if we add a second constructor?

I'd say it's pretty confusing, and all this confusion isn't really necessary because there are good constructs ("constructor" and field assignment shorthands) that already allow you to do the necessary things with about the same amount of code.

So there are cons, and no pro's.

To conclude, I wouldn't want these kinds of constructs in my code, which is why I doubt that this will ever be supported.

0
XPD On

In C# language executable expressions should reside in a method. Classes itself are not executable. They provide the blueprint for an object on how to behave. Classes can only have, methods and properties. In C# properties, events and delegates are also allowed in a class. But internally properties, events and delegates are also methods and variables.

public partial class Form1 : Form
{
string b;
b = "something";
public Form1()
{
    InitializeComponent();
}
}

in here, string b; is a variable declaration. b="something" is an executable expression. So you cannot have b="something" inside the class directly. But string b = "something"; is a special syntax which called as initialization. That is defined in C# language. Otherwise you should move b="something" to some method including constructor. Internally initialization code runs when creating a new object, before the constructor is called and we can think it as a part of the constructor.