0

In C#, why doesn't field initializer syntax not throw compilation errors, however, method calls do? For example,

class SomeOtherClass {
    void SomeMethod() { }
}

class SomeClass {

    SomeOtherClass someOtherObject = new SomeOtherClass();
    someOtherObject.SomeMethod();
}

Why does the someOtherObject initialization, which essentially is a constructor call work? My understanding is that a constructor is also a method. However the second line, where there is a method call, does not work. Is this a language design choice?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Saikat Das
  • 358
  • 2
  • 15
  • A class is just a skeleton, it can not on its own perform operations/action. Assume suppose it is allowed then simply you don't have control over the class behavior i.e. you don't have a way to do a set of operations as and when required in a controlled manner. But it is perfectly fine to invoke methods/actions from within constructor so that class instantiation itself can do some basic stuff for you. + OOPS (object orientation)!! Hope you get it.. – Siva Gopal Nov 21 '15 at 16:47
  • + Check [this SO](http://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – Siva Gopal Nov 21 '15 at 16:59
  • Right, that clears it up a bit. Thanks. – Saikat Das Nov 21 '15 at 17:04

2 Answers2

2
SomeOtherClass someOtherObject = new SomeOtherClass();

is syntactic sugar for this anyway:

SomeOtherClass someOtherObject;

public SomeClass() {
    someOtherObject = new SomeOtherClass()
}

So nothing is executed outside of the constructor. The compiler will create an empty constructor if it doesn't exist and initialize someOtherObject.

Saragis
  • 1,782
  • 6
  • 21
  • 30
0

A Class contains attributes and methods declarations and definitions only. Attributes can be initialized right there as you're doing

SomeOtherClass someOtherObject = new SomeOtherClass();

and in the constructors.

Doing

someOtherObject.SomeMethod();

is neither declaration/definition nor initialization. Which is not allowed.