Skip to content

Instantly share code, notes, and snippets.

@ChaseFlorell
Created January 27, 2016 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChaseFlorell/882935d282d5516980e5 to your computer and use it in GitHub Desktop.
Save ChaseFlorell/882935d282d5516980e5 to your computer and use it in GitHub Desktop.
Implicit type example
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