0

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.

Edited by Derek_11: Found a workaround

2
Contributors
3
Replies
26
Views
6 Months
Discussion Span
Last Post by ddanbe
1

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

0

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!

1

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.