I was having trouble setting properties and realized I could only set the properties within a function or method. My question is why is this the case?
Here is my code that works:
public class SomeClass
{
Car car = new Car();
public Car JustAMethod()
{
Car car = new Car();
car.year = 2012;
return car;
}
}
Why doesn’t this work:
public class SomeClass
{
Car car = new Car();
car.year = 2012;//I get an error here
}
The language specification (for the most part) forbids the execution of arbitrary statements at the class level. All that can be done is to specify default values for static or instance members of the class.
All code, generally speaking, must be executed within methods of a class.
As AntLaC mentioned, you can get around this by specifying the value using the object initialization syntax. Since objects can be defined at the class level (as “default values for static or instance members”), using syntax like the below will also work: