views:

70

answers:

5

I am trying to use autoimplemented properties. It shows me error

    public OpenMode OpenFor
    {
        get;//must declare a body because it is not marked as abstract, partial or external. Why so 
        set
        {
            if (value == OpenMode.Add)
            {
                btnAddGuest.Text = "Save";
                btnUpdatePreference.Visible = false;
                dgvGuestInfo.ClearSelection();
            }
            else if (value == OpenMode.Update)
            {
                btnAddGuest.Text = "Update";
                btnUpdatePreference.Visible = true;
            }
        }
    }
+5  A: 

You must implement both a getter and setter if you implement one of them. You can auto implement only both:

public OpenMode OpenFor
{
   get; 
   set;
}

You may consider to use a backing field:

private OpenMode openFor;

public OpenMode OpenFor
{
   get
   {
      return openFor;
   }
   set 
   {
      openFor = value;
      //...
   }
}
Simon
@Simon: thx, i didn't expected this reason. But may be it is a functionality
Shantanu Gupta
A: 

autoimplementation works only for the simple usecase that set and get have no custom body

Jack
A: 

To use just get; you need to use just set; as well. In this case you'd have an implicit variable. When you declare a body for set, that doesn't work. Ask yourself the question; how can you get anything you can never set?

k_b
A: 
private OpenMode _openFor;
public OpenMode OpenFor
{
    get{return _openFor;}
    set{
        _openFor = value;
        SetOpenFor(value);
    }
}

private void SetOpenFor(OpenMode mode)
{
 if (mode== OpenMode.Add)
 {
     btnAddGuest.Text = "Save";
     btnUpdatePreference.Visible = false;
     dgvGuestInfo.ClearSelection();
 }
 else if (mode == OpenMode.Update)
 {
     btnAddGuest.Text = "Update";
     btnUpdatePreference.Visible = true;
 }
}
TheVillageIdiot
A: 

Also note that the auto-implemented properties also listen to access modifiers:

public string Foo { get; private set; }

Though you still need to define both.

In your example, it looks like you don't need the get. You aren't storing the value into a local field either, so it looks like your property should be a method.

Alternatively, your get could infer the value from the state of the buttons you are modifying in the set - but this is starting to get silly.

Adam