adaam
adaam

Reputation: 3706

Auto setting properties in C#

I have a class called Place that uses getters and setters like so:

public class Place
{
    public string Address { get; set; }
    public GeoCoordinate Location
    {
        set
        {
            // geocode Address field and receive Geocoding response, initializing a new instance of GeoCoordinate class - my attempt below..
            IGeocoder geocoder = new GoogleGeocoder();
            IEnumerable<Address> matchedAddresses = geocoder.Geocode(this.Address);
            this.Location = new GeoCoordinate(matchedAddresses.Cast<Address>().First().Coordinates.Latitude, matchedAddresses.Cast<Address>().First().Coordinates.Longitude);
        }
        get
        {
            return this.Location;
        }
    }
}

And say I want to create a new instance of the class Place like so:

    Place thePlace = new Place()
    {
        Address = "123 Fake Street, London"
    };

How would I automatically trigger the setter for the Location variable when the Address property is set so that the address fed in is automatically geocoded and the GeoCoordinate object is set automatically?

Upvotes: 1

Views: 118

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726469

You would need to change the Address from an auto-property to a "regular" one (i.e. a property composed from a variable and a getter/setter pair), like this:

private string address;
public string Address {
    get {return address;}
    set {
        // Prepare the location
        GeoCoordinate loc = GetGeoCoordinateFromAddress(value);
        // Store address for future reference
        address = value;
        // Setting the location by going through the property triggers the setter
        Location = loc;
    }
}

Upvotes: 3

BradleyDotNET
BradleyDotNET

Reputation: 61339

The set semantic doesn't make any sense for what you are doing (you aren't even using the value keyword). At worst, it makes this code nonsense:

obj.Location = someGeoCoordiante;

You could easily just put the logic in the get piece (and not define a set). Of course this will re-run your calculation every time you access it. If that is a problem, still remove the set and have the setter for the Address property recalculate the locally stored Location field.

Upvotes: 1

Andrew
Andrew

Reputation: 5083

Change public string Address { get; set; } to

private string _address;
public string Address
{
    get { return _address; }
    set
    {
        // code to set geocoder
        _address = value;
    }
}

By the way, this code here

public GeoCoordinate Location
{
    ...
    get
    {
        return this.Location;
    }
}

will recurse forever. You should think about reworking that.

Upvotes: 1

Related Questions