Search code examples
c#winformsencapsulationgmap.net

How make so that by pressing the button in one form created object and passed to the other?


I creating a simple app working with maps on c#, using GMap.NET control for it. So, my question is: I want to make a polygons, polylines and markers in one form using another. My code relating to it is:

First form (MapModule):

    GMapOverlay polygonOverlay = new GMapOverlay("polygons");
    GMapOverlay markersOverlay = new GMapOverlay("markers");
    GMapOverlay polylineOverlay = new GMapOverlay("polylines");

Second form (NewFile):

public MapModule _MapModule;
        public Newfile(MapModule MapModule)
        {
            InitializeComponent();
            _MapModule = MapModule;
        }
private void addpolygon_Click(object sender, EventArgs e)
        {
            GMapPolygon polygon = new GMapPolygon(points, "What you need");
            _MapModule.polylineOverlay.Polygons.Add(polygon);
        }

The output is:

'GoogleMaps.MapModule.polylineOverlay' is inaccessible due to its protection level

I think, it must be very simple, but I am completely new in programming.

Valid XHTML.


Solution

  • The first quick and dirty option is to make that object public:

    public GMapOverlay polylineOverlay = new GMapOverlay("polylines");
    

    But that's not a good practice, as this way you are breaking the encapsulation principle and you lose control about what happens with your object. If that variable at some point has garbage, it will be harder for you to know why that occurred.

    An alternative is to create a getter, so the reference can be accessed publicly although not modified.

    private GMapOverlay polylineOverlay = new GMapOverlay("polylines");
    public GMapOverlay PolylineOverlay
    {
        get
        {
            return this.polylineOverlay;
        }
    }
    

    The containing class can access both, but other classes can access only the public property.

    Also, if you don't want this object to be created until it's first used, you could do this instead:

    private GMapOverlay polylineOverlay;
    public GMapOverlay PolylineOverlay
    {
        get
        {
            if (this.polylineOverlay == null)
                 this.polylineOverlay = new GMapOverlay("polylines")
            return this.polylineOverlay;
        }
    }
    

    Although in this case, you should use the public property inside your class, or instantiate it somewhere else.