Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-3.5

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!

like image 502
Matt Avatar asked Jul 13 '09 20:07

Matt


People also ask

What are auto-implemented properties in C#?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is Auto property Initializers?

Auto-property initializers are basically a shortcut to setting the property value in the constructor. I wasn't overly excited about the new feature at first, but I think it makes the intention a lot more clear when you see the initial value on the same line as the auto-implemented property.

What is a backing field C#?

A private field that stores the data exposed by a public property is called a backing store or backing field. Fields typically store the data that must be accessible to more than one type method and must be stored for longer than the lifetime of any single method.


1 Answers

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;
    }
}
like image 82
Brandon Avatar answered Oct 08 '22 01:10

Brandon