warning CS0618: 'System.Net.IPAddress.Address' is obsolete

For a call to a WinApi function I needed to convert an IP Address to an Integer in C#.

This can be done using the System.Net.IPAddress class:

using System.Net;

IPAddress ipa = IPAddress.Parse("10.4.2.91");

uint ip = (uint)ipa.Address;

Although this works, the compiler issues a warning: 

warning CS0618: ‘System.Net.IPAddress.Address’ is obsolete: ‘This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202′

This warning is issued because the Address property is not IPv6 compatible. The warning can be suppressed like this:

using System.Net;

IPAddress ipa = IPAddress.Parse("10.4.2.91");

#pragma warning disable 612, 618
uint ip = (uint)ipa.Address;
#pragma warning restore 612, 618

But it would be better to use the non deprecated GetAddressBytes() Method:

using System.Net;

IPAddress ipa = IPAddress.Parse("10.4.2.91");
uint ip = System.BitConverter.ToUInt32(ipa.GetAddressBytes(), 0);

Was once an enthusiastic PepperByte employee but is now working elsewhere. His blogs are still valuable to us and we hope to you too.