0

I am trying to get the length of a drawn line to a textbox but its throwing an NullReferenceException at var length = f.ToShape().ToGeometry().Length;. How to fix this Exception. what mistake i am making? Although i am using GIS library but i think its a problem related to C# thats why i am posting the question here rather in GIS section.

Code:

private void map1_MouseClick_1(object sender, MouseEventArgs e)
    {
        // digitizing
        if (amDigitizing == true)
        {
            DotSpatial.Topology.Coordinate c = new DotSpatial.Topology.Coordinate();
            System.Drawing.Point p = new System.Drawing.Point();
            p.X = e.X;
            p.Y = e.Y;
            c = map1.PixelToProj(p);

            myDigitizedPoints.Add(c);
        }
    }
    private void map1_MouseDoubleClick_1(object sender, MouseEventArgs e)
    {
        // Double click ends digitizing
        if (amDigitizing == true)
        {
            DotSpatial.Topology.Coordinate c = new DotSpatial.Topology.Coordinate();
            System.Drawing.Point p = new System.Drawing.Point();
            p.X = e.X;
            p.Y = e.Y;
            c = map1.PixelToProj(p);
            myDigitizedPoints.Add(c);

            amDigitizing = false;


            DotSpatial.Data.Feature f = new DotSpatial.Data.Feature(DotSpatial.Topology.FeatureType.Line, myDigitizedPoints);
            DotSpatial.Data.FeatureSet fs = new DotSpatial.Data.FeatureSet();
            fs.AddFeature(f);

            fs.Projection = map1.Projection;
            fs.Name = "Mine";
            //fs.SaveAs(GraphicsPathExt, true);
            //LineLyr = (DotSpatial.Controls.MapLineLayer)map1.AddLayer(GraphicsPathExt);
            LineLyr = (MapLineLayer)map1.Layers.Add(fs);

            var length = f.ToShape().ToGeometry().Length;
            textBox1.Text = length.ToString();
        }


    }  
Vanadium90
  • 111
  • 1
  • 6
  • Simply enough, why dont you just check if f is null then check if ToShape returns null then check if ToGeometry returns null – misha130 May 08 '15 at 23:38
  • The code you posted does not show the error you describe. It should not be possible for `new` to return `null`; I suspect code you have not shown us is changing it. You have to use a debugger to track this down as shown in [What is a NullReferenceException](http://stackoverflow.com/questions/4660142/). – Dour High Arch May 09 '15 at 00:24

1 Answers1

2

To fix your exception just add some test :

if(f != null) 
{
    var shape = f.ToShape();
    if(shape != null)
    {
       var geomtry = shape..ToGeometry();
       if(geomtry != null)
          var length = geomtry.Length; 
    }
}
MRebai
  • 5,344
  • 3
  • 33
  • 52