Automatic Properties in C# 3 - Must declare a body for get if I declare one for set?

.net-3.5, c#

Solution

If you're going to add logic in the set, you need to add it into the get as well. Notice in your set you're not actually setting a value to anything?

Add a backing field,

private string _vin;

and return that in the get.

public string VIN
{
    get { return _vin; }
    set
    {
      if (value.Length != 17) 
        throw new ArgumentOutOfRangeException("VIN", "VIN must be 17 characters"); 
      else
        _vin = value;
    }
}

Problem

I'm using VS 2008, and in my property pages for the project I see that I'm targeting .Net 3.5. Here is the error I'm getting when trying to compile: AMSDataModels.Vehicle.VIN.get' must declare a body because it is not marked abstract, extern, or partial And here is the code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AMSDataModels { public class Vehicle { //NodeID for datastore persistance public Guid NodeID { get; set; } public string VIN { get; set { if (value.Length != 17) throw new ArgumentOutOfRangeException("VIN", "VIN must be 17 characters"); } } public string Make { get; set; } public string Model { get; set; } } } ``` If I strip the body from set so that its just: ``` public string VIN { get; set; } ``` All works, but I lose my ability to check the VIN as it is set. Does anyone have a suggestion of how to fix this or a better way to approach the problem at hand? I really like the shorthand notation - but verifying the legitimacy of input is important too!

Original source