3

Is it possible to initialize the variable like this:

class A
{
public int variable;
}
class B : A
{
variable = 123;
}

instead of using contructor like this? :

class A
{
   public int variable;
}

class B : A
{
   public B()
   {
   variable = 123;
   }
}

Here : Initialize class fields in constructor or at declaration?

These two ways seems to be equivalent, but using the 1st way in derived class seems to be illegal. Then, is it possible to initialize variables in the other way than using constructor?

Community
  • 1
  • 1
Smorts
  • 95
  • 6

1 Answers1

1

You can initialize a field of a class, when you declare it as below:

public class Example
{
    public int Number = 3;
}

or you can do so in a constructor like below:

public class Example;
{
    public int Number;
    public Example(int number)
    {
        Number = number;
    }
}

There are only these two options. In your case you have a base class, where you declare a field. So this field can be initialized either at the declaration or through a constructor. This is why it's illegal the following:

class A
{
    public int variable;
}

class B : A
{
    variable = 123;
}

Then, is it possible to initialize variables in the other way than using constructor?

Of course it is possible, but you have to do this at the base class:

class A
{
    public int variable = 123;
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • Ok, but can i somehow change the value of this variable in derived class, after i initialize it in base class? – Smorts Jan 08 '17 at 15:53
  • Of cousre you can. In any *method* of your derived class you can refer to this variable using it's name `variable` and set there the new value. – Christos Jan 08 '17 at 15:56
  • So in constructor etc. But i can't just type `variable = something` in derived class definition right? – Smorts Jan 08 '17 at 15:59
  • @Smorts Exactly ! By the way this is not allowed at all even if you are talking about only a class (no inheritance, base and derived class). It is syntactically incorrect you have the name of a variable as a member of a class, it's not a valid class member. For further information regarding the members of a class have a look at https://msdn.microsoft.com/en-us/library/ms173113.aspx. – Christos Jan 08 '17 at 16:03