mHelpMe
mHelpMe

Reputation: 6668

get must declare a body it is not marked abstract, extern, or partial

I wrote the line of code below but the an error was highlighted, below:

get must declare a body it is not marked abstract, extern, or partial

I don't understand what the problem is? Why can't the set call a method without mucking up the get?

 public string NoteColour { get; set { SetFontColour(value); } }

Upvotes: 5

Views: 6799

Answers (3)

Bastian Thiede
Bastian Thiede

Reputation: 468

If you don't write a body for get and set a macro is called which adds an hidden private field for your property in order to store the actual value. This is needed because a property has no memory associated with it and simply acts like a method working on your class object. It gives you the convince not to write explecit getter or setter methods like in old times.

If you want to do custom things (others than simply encapsulate a field), you have to declare both bodys since the macro does not know which field it should return.

Just for completeness:

private string noteColor = string.Empty;

public string NoteColour
{
    get
    {
        return this.noteColor;
    }
    set
    {
        // add custom actions needed here
        this.noteColor = value;
    }
}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

The error suggests that you need to provide the body for your get method. So if you have created property by your own then you have to implement either both get and set or none.

public string NoteColour 
{ 
   get 
   { 
     return GetMethod(); 
   } 
   set 
   { 
     SetFontColour(value); 
   } 
}

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 157098

You have to supply an implementation for the get since the compiler only allowed auto-implemented properties if both the get and set have no implementation.

If you implement either of them, you have to give an implementation for the other one too.

I expect to have something like this:

 public string NoteColour { get { return GetFontColor(); } set { SetFontColour(value); } }

Upvotes: 9

Related Questions