Created
May 23, 2017 09:26
-
-
Save MichaelRumpler/c201147d23854ef3e1f17c749e30b3fd to your computer and use it in GitHub Desktop.
Version class
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; | |
using System.Linq; | |
namespace RoyalMobileApps.XF.Helpers | |
{ | |
public struct Version | |
{ | |
private readonly int[] parts; | |
public Version(string version) | |
{ | |
if(string.IsNullOrWhiteSpace(version)) | |
{ | |
parts = new int[0]; | |
return; | |
} | |
parts = version.Trim() // remove whitespace | |
.Split('.') // to string[] | |
.Select(s => int.Parse(s)) // to int[] - may throw an exception | |
.ToArray(); | |
} | |
public static explicit operator Version(string version) | |
{ | |
return new Version(version); | |
} | |
public override bool Equals(object obj) | |
{ | |
if (!(obj is Version)) | |
return false; | |
var other = (Version)obj; | |
return this == other; | |
} | |
public override int GetHashCode() | |
{ | |
return parts.GetHashCode(); | |
} | |
public override string ToString() | |
{ | |
return string.Join(".", parts); | |
} | |
#region Comparissons | |
public static bool operator ==(Version a, Version b) { return Compare(a, b) == 0; } | |
public static bool operator !=(Version a, Version b) { return Compare(a, b) != 0; } | |
public static bool operator < (Version a, Version b) { return Compare(a, b) < 0; } | |
public static bool operator > (Version a, Version b) { return Compare(a, b) > 0; } | |
public static bool operator <=(Version a, Version b) { return Compare(a, b) <= 0; } | |
public static bool operator >=(Version a, Version b) { return Compare(a, b) >= 0; } | |
/// <summary> | |
/// Compares the given Versions | |
/// </summary> | |
/// <param name="a"></param> | |
/// <param name="b"></param> | |
/// <returns>-1 if a is smaller, 0 if they are equal and 1 if a is bigger</returns> | |
private static int Compare(Version a, Version b) | |
{ | |
int i = 0; | |
var l = Math.Min(a.parts.Length, b.parts.Length); | |
while (i < l && a.parts[i] == b.parts[i]) | |
i++; | |
if(i<l) // they didn't match | |
return a.parts[i] < b.parts[i] ? -1 : 1; | |
// at least one of the Versions is at its end, check there is anything but 0 remaining | |
if (l < a.parts.Length && a.parts.Skip(l).Any(v => v != 0)) // a is longer && there are non zero numbers in it => a is bigger | |
return 1; | |
if (l < b.parts.Length && b.parts.Skip(l).Any(v => v != 0)) // b is longer && there are non zero numbers in it => b is bigger | |
return -1; | |
return 0; | |
} | |
#endregion Comparissons | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment