Search code examples
c#castingnullreferenceexceptionsqlgeometry

Cast SqlDouble to double? type causes SqlDouble.Value to raise null value exception


I am trying to construct a linestring using SqlGeometryBuilder.

SqlGeometry point = line.STPointN(x)
gb.BeginFigure((double)point.X, (double)point.Y, (double?)point.Z, (double?)point.M);

The .Z and .M properties of the SqlGeometry return as type SqlDouble, so I tried casting them both to double?. However, casting these properties seems to call .Value on the property which will throw a null exception rather than returning null, breaking my code.

Is there a way to cast which doesn't invoke .Value for the SqlGeometry Z and M values?


Solution

  • Can this help?

    SqlGeometry point = line.STPointN(x)
    gb.BeginFigure((double)point.X, (double)point.Y, point.HasZ ? (double?)point.Z : (double?)null, point.HasM ? (double?)point.M : (double?)null );