Reputation: 149
I've quite a simple question. Why can't you assign property a value outside of a method, like shown below? Whats the difference between doing it inside a method and outside a method?
Please see below:
Edit:
Below is what I was trying to do, hence the question above.
Upvotes: 1
Views: 1636
Reputation: 112259
You can exectue code when the class is created. Use a constructor for this. It looks like a method but has no return type and its name is the same as the class name:
public class SubClass : BaseClass
{
public SubClass()
{
Build = "Hello"; // Build must be either public or protected in the base class.
// SubClass inherits Build, therfore no "base." is required.
}
// Other methods to go here
}
If the base class has a constructor having parameters, you must pass those the base class' constructor:
public class BaseClass
{
public BaseClass(string build)
{
Build = build;
}
public string Build { get; private set; }
}
public class SubClass : BaseClass
{
public SubClass()
: base("Hello") // Calls the base class' constructor with "Hello"
{
}
}
Now you can call:
var baseClass = new BaseClass("Hello");
// or
var subClass = new SubClass();
Both assign "Hello"
to Build
.
Upvotes: 1
Reputation: 61339
Anything inside of a classes root scope is just part of the class definition. The class definition defines what properties the object has, what methods can be invoked on it, the ways to construct the object, etc.
Putting an actual statement here doesn't make any sense; when would it run? Actual execution of code is not part of a class definition.
Thus, all statements must reside in a method, since methods are the only things that actually execute statements.
Upvotes: 2