c# - Chaining to clean up CompareTo -



c# - Chaining to clean up CompareTo -

every time need write compareto method in c#, hate fact can't chain tests , results in javascript:

function int compareto(a, b) { homecoming a.value1 - b.value1 || a.value2 - b.value2 || a.value3 - b.value3; }

instead in c# looks like:

int compareto(object obj) { var other = obj myclass; if (other == null) homecoming 0; int result = value1 - other.value1; if (result != 0) homecoming result; result = value2 - other.value2; if (result != 0) homecoming result; homecoming value3 - other.value3; }

is there way write above 'cleaner'? doesn't have one-liner in javascript, should more readable , less error-prone.

using generic extension method nullablecompareto can create utilize of ?? operator refactor compareto method to:

int compareto(object obj) { var other = obj myclass; if (other == null) homecoming 0; homecoming value1.nullablecompareto(other.value1) ?? value2.nullablecompareto(other.value2) ?? value3.compareto(other.value3); }

extension method

public static class comparableextensions { /// <summary> /// same compareto returns null instead of 0 if both items equal. /// </summary> /// <typeparam name="t">icomparable type.</typeparam> /// <param name="this">this instance.</param> /// <param name="other">the other instance.</param> /// <returns>lexical relation between , other instance or null if both equal.</returns> public static int? nullablecompareto<t>(this t @this, t other) t : icomparable { var result = @this.compareto(other); homecoming result != 0 ? result : (int?)null; } }

c#

Comments

Popular posts from this blog

javascript - I need to update the text of a paragraph by inline edit -

javascript - THREE.js reposition vertices for RingGeometry -

assembly - What is the addressing mode for ld, add, and rjmp instructions? -