1

What is the difference between below 2 ways of assigning values for variables of a class.

Class A{
 Private Variable v = someValue;
}

vs

Class A{
    private Variable v;

    //constructor
    public A(){
        this.v = someValue;
    }
}

Can someone please explain?

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87

3 Answers3

2

There is no real difference from a code execution point of view.

As a previous answer says, I prefer declaring the variable outside of the constructor; for example:

public class A {
    private int aValue = 100;
}

Instead of

public class A {
    private int aValue;
    public A() {
       this.aValue = 100;
    }
}

The reason being that if you have multiple constructors, you do not have to keep writing this.aValue = 100; and you are unable to "forget" to initialize the variable in a constructor.

As others have said however, there are times when it is better to initialize the variable in the constructor.

  • If it will change based on values passed to it via the constructor, obviously initialize it there.

  • If the variable you are initializing may throw an error and you need to use try / catch - it is clearly better to initialize it in the constructor

  • If you are working on a team that uses a specific coding standard and they require you to initialize your variables in the constructor, you should do so.

Given freedom and none of the above, I still declare it at the top - makes it much easier to find all of your variables in one place (in my experience).

See this duplicate answer: https://stackoverflow.com/a/3919225/1274820

Community
  • 1
  • 1
user1274820
  • 7,786
  • 3
  • 37
  • 74
1

What is the difference between below 2 ways of assigning values for variables of a class.

Generally nothing, but ... class constructor is an entry point when creating a new instance, so all assignments should be done there for readability and maintainability.

When you want create a new instance you start reading a source code at the constructor. Here is an example. All informations about new instance are in one proper place.

public class C {
    private int aValue;
    private int bValue;
    private int cValue;
    private int dValue;

    public C(int a, int b) {
       this.aValue = a;
       this.bValue = b;
       this.cValue = a * b;
       this.dValue = 1000;
    }
}
John Smith
  • 1,091
  • 9
  • 17
0

If you look at the MSIL of this class:

namespace Demo
{
    public class MyClass
    {
        private string str = "hello world";
        private int b;

        public MyClass(int b)
        {
            this.b = b;
        }
    }
}



.method public hidebysig specialname rtspecialname 
        instance void  .ctor(int32 b) cil managed
{
  // Code size       25 (0x19)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldstr      "hello world"
  IL_0006:  stfld      string Demo.MyClass::str  <---- RIGHT HERE
  IL_000b:  ldarg.0
  IL_000c:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0011:  ldarg.0
  IL_0012:  ldarg.1
  IL_0013:  stfld      int32 Demo.MyClass::b
  IL_0018:  ret
} // end of method MyClass::.ctor

You can see that the constructor is "injected" with the assignment of this.str = "hello world".

So once your code is compiled, there is no difference what so ever. Yet, there are quite a few good reasons why you should not do it (user1274820's answer has some them)

shay__
  • 3,815
  • 17
  • 34