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!
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With