Rayshawn
Rayshawn

Reputation: 2617

Why can't I set the property value of a class object without being in a method?

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
}

Upvotes: 0

Views: 2299

Answers (5)

AntLaC
AntLaC

Reputation: 1225

If you want to set specific properties you can try this without being in a method

Car car = new Car()
          {
             year = 2012
          };

Upvotes: 3

Platinum Azure
Platinum Azure

Reputation: 46193

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:

public class SomeClass
{
    Car car = new Car() {
        year = 2012;
    };
}

Upvotes: 5

Omar
Omar

Reputation: 16623

You can't set the property in that way, it isn't allowed. You can do it in a constructor/ in a method/in a property. Or in this way:

public class SomeClass{        
    Car car = new Car(){ year = 2012 };
}

Or you can pass to the constructor your value:

public class Car{
    public int year;
    public Car(int year){
        this.year = year;
    }
}

And:

public class SomeClass{        
    Car car = new Car(2012);
}

Upvotes: 0

Bob Horn
Bob Horn

Reputation: 34297

The simple answer is that those are just the rules of the language. However, you have a few options:

Create a constructor so that Car takes a year:

public class SomeClass
{        
    Car car = new Car(2012);
}

Use object initializers:

public class SomeClass
{        
    Car car = new Car() { Year = 2012 };
}
Use a method:
public class SomeClass
{        
    Car car = InitializeCar(2012);

    private Car InitializeCar(int year)
    {
        Car car = new Car();
        car.Year = 2012;

        return car;
    }
}    

Upvotes: 1

Adam
Adam

Reputation: 15803

Because that is the way the language specification requires it.

Imagine the mess that would happen if it were possible to write anything anywhere you liked: We'd have ended up with PHP, and that was certainly not a design goal of C#.

Upvotes: 4

Related Questions