Created
February 25, 2015 21:00
-
-
Save jbrestan/8143fe86c2bac1035620 to your computer and use it in GitHub Desktop.
C# operator overloading abuse. IIRC inspired by Jon Skeet's operator abuse article
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
[TestClass] | |
public class OperatorAbuseTest | |
{ | |
[TestMethod] | |
public void TestTheAbuse() | |
{ | |
var repeat = Operators.Repeat<string>(); | |
var join = Operators.Join<string>(); | |
var result = "Hello" <repeat> 3 <join> ","; | |
var expected = "Hello,Hello,Hello"; | |
Assert.AreEqual(expected, result); | |
} | |
} | |
public static class Operators | |
{ | |
public static Operator<T, int, IEnumerable<T>> Repeat<T>() | |
{ | |
return new Operator<T, int, IEnumerable<T>>(Enumerable.Repeat); | |
} | |
public static Operator<IEnumerable<T>, string, string> Join<T>() | |
{ | |
return new Operator<IEnumerable<T>, string, string>((values, separator) => string.Join(separator, values)); | |
} | |
} | |
public class Operator<TLeft, TRight, TResult> | |
{ | |
private readonly Func<TLeft, TRight, TResult> func; | |
public Operator(Func<TLeft, TRight, TResult> func) | |
{ | |
this.func = func; | |
} | |
public static PartialOperator<TLeft, TRight, TResult> operator <(TLeft lhs, Operator<TLeft, TRight, TResult> op) | |
{ | |
return new PartialOperator<TLeft, TRight, TResult>(lhs, op.func); | |
} | |
public static PartialOperator<TLeft, TRight, TResult> operator >(TLeft lhs, Operator<TLeft, TRight, TResult> op) | |
{ | |
return new PartialOperator<TLeft, TRight, TResult>(lhs, op.func); | |
} | |
} | |
public class PartialOperator<TLeft, TRight, TResult> | |
{ | |
private readonly Func<TLeft, TRight, TResult> func; | |
private readonly TLeft left; | |
internal PartialOperator(TLeft left, Func<TLeft, TRight, TResult> func) | |
{ | |
this.left = left; | |
this.func = func; | |
} | |
public static TResult operator >(PartialOperator<TLeft, TRight, TResult> op, TRight rhs) | |
{ | |
return op.func(op.left, rhs); | |
} | |
public static TResult operator <(PartialOperator<TLeft, TRight, TResult> op, TRight rhs) | |
{ | |
return op.func(op.left, rhs); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment