Transforming business operations through innovation

Developer Blog

Tips and tricks for developers.

Magnetic Declination in C#

Calculating magnetic field data such as magnetic declination in C# is a breeze. Thanks to the CoordinateSharp team, you can do it in just a few lines of code.

Step 1

To get started, download the CoordinateSharp.Magnetic nuget package via your developer environment’s nuget package installer.


Step 2

Add the below using statements to your code.

using CoordinateSharp;
using CoordinateSharp.Magnetic;

Step 3

Create a Coordinate and gather its magnetic data.

//Set your lat, long and date parameters
double latitude = 45;
double longitude = -121;
DateTime date = new DateTime(2020, 10, 1); 

//Create a Coordinate
Coordinate c = new Coordinate(longitude, latitude, date);

//Populate the magnetic data using the World Magnetic Model 2020-2025
Magnetic m = new Magnetic(c, DataModel.WMM2020);

//View declination
m.MagneticFieldElements.Declination; //14.673069

Notes

There are other useful magnetic data points within the Magnetic object such as uncertainty and secular variations. More example of calculating magnetic data with CoordinateSharp can be found in the CoordinateSharp Developer Guide.

CoordinateSharp is a powerful, lightweight .NET library that can also convert geographic coordinates, calculate sun and moon data and even perform distance calculations. Be sure to check it out.