Hi!

I have encountered a small issue when attempting to create getters and setters in C#. I've been following along a course in unity and tried to replicate what the tutor had written in his C# scripts. As far as I can tell, everything is spot on and I can't seem to find what's causing the error -- Visual Studio suggests adding semi-colons after the 'get' and 'set' keywords, but I don't think that's correct course of action. Here is a snippet of the code that causes the error. Perhaps someone could explain to me what I'm doing wrong and give me some helpful pointers as to how I can go about solving this error.

Presume I've declared two private variables in my class: string name and float health.

public string Name()
{
    get {
        return name;
    }
    set {
        name = value;
    }
}

public float Health()
{
    get {
        return health;
    }
    set {
        health = value;
    }
}

When I attempt to compile this code it throws an error: "expecting ;" with Visual Studio highlighting the 'get' and 'set' keyword. Any ideas?

Edit: The workarounds I've found is implementing an accessor and mutator method for each variable (the Java way) - but I was hoping I could take advantage of C#'s get and set clause to simplify my code.

Recommended Answers

All 3 Replies

Properties are not methods, so remove the () on line 1 and on line 11. Happy programming!

Thank you, that worked just fine! Can't believe I didn't spot that. Guess I had properties mixed up with accessors and mutators, so I never thought twice before declaring them as methods. This saved me from a ton of hassle and I'm happy to mark this as solved. Hugely appreciated!

At first sight C# and Java look very similar, but they are totally different languages. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.