Created
January 27, 2016 18:56
-
-
Save ChaseFlorell/882935d282d5516980e5 to your computer and use it in GitHub Desktop.
Implicit type example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Foo.Bar.Baz | |
{ | |
/// <summary> | |
/// Allows us to define actual LatLong in our models and have all platforms handle them whether | |
/// they use float, decimal, or double as their underlying types. | |
/// </summary> | |
/// <remarks>Our "opinion" is that at the end of the day, a <see cref="LatLong"/> is simply a <see cref="Double"/></remarks> | |
public struct LatLong | |
{ | |
public LatLong(double value) | |
{ | |
_value = value; | |
} | |
private readonly double _value; | |
/// <summary> | |
/// Allows direct casting from a LatLong to a Double | |
/// </summary> | |
/// <param name="value"><see cref="LatLong"/> to be cast</param> | |
/// <returns><see cref="Double"/></returns> | |
public static implicit operator double(LatLong value) | |
{ | |
double result; | |
if (double.TryParse(value.ToString(), out result)) | |
{ | |
return result; | |
} | |
var msg = string.Format("Cannot cast LatLong value: {0} to double.", value); | |
throw new InvalidCastException(msg); | |
} | |
/// <summary> | |
/// Allows direct casting from a Double to a LatLong | |
/// </summary> | |
/// <param name="value"><see cref="Double"/> to be cast</param> | |
/// <returns><see cref="LatLong"/></returns> | |
public static implicit operator LatLong(double value) | |
{ | |
return new LatLong(value); | |
} | |
/// <summary> | |
/// Allows direct casting from a Decimal to a LatLong | |
/// </summary> | |
/// <param name="value"><see cref="Decimal"/> to be cast</param> | |
/// <returns><see cref="LatLong"/></returns> | |
public static implicit operator LatLong(decimal value) | |
{ | |
return new LatLong(Convert.ToDouble(value)); | |
} | |
/// <summary> | |
/// Allows direct casting from a Float to a LatLong | |
/// </summary> | |
/// <param name="value"><see cref="Single"/> to be cast</param> | |
/// <returns><see cref="LatLong"/></returns> | |
public static implicit operator LatLong(float value) | |
{ | |
return new LatLong(Convert.ToDouble(value)); | |
} | |
public override string ToString() | |
{ | |
return _value.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment