Can I create ternary operators in C#?
c#, ternary-operator
Solution
Don't believe the haters ;)
You can do this in C#. Here's an example implementation — I based the chaining off the way that Icon does theirs... if a comparison succeeds, the result is that of the right parameter, otherwise a special "failed" result is returned.
The only extra syntax you need to use is the call to `Chain()` after the first item.
class Program
{
static void Main(string[] args)
{
if (2.Chain() < 3 < 4)
{
Console.WriteLine("Yay!");
}
}
}
public class Chainable<T> where T : IComparable<T>
{
public Chainable(T value)
{
Value = value;
Failed = false;
}
public Chainable()
{
Failed = true;
}
public readonly T Value;
public readonly bool Failed;
public static Chainable<T> Fail { get { return new Chainable<T>(); } }
public static Chainable<T> operator <(Chainable<T> me, T other)
{
if (me.Failed)
return Fail;
return me.Value.CompareTo(other) == -1
? new Chainable<T>(other)
: Fail;
}
public static Chainable<T> operator >(Chainable<T> me, T other)
{
if (me.Failed)
return Fail;
return me.Value.CompareTo(other) == 1
? new Chainable<T>(other)
: Fail;
}
public static Chainable<T> operator ==(Chainable<T> me, T other)
{
if (me.Failed)
return Fail;
return me.Value.CompareTo(other) == 0
? new Chainable<T>(other)
: Fail;
}
public static Chainable<T> operator !=(Chainable<T> me, T other)
{
if (me.Failed)
return Fail;
return me.Value.CompareTo(other) != 0
? new Chainable<T>(other)
: Fail;
}
public static bool operator true(Chainable<T> me)
{
return !me.Failed;
}
public static bool operator false(Chainable<T> me)
{
return me.Failed;
}
public override bool Equals(object obj)
{
return Value.Equals(obj);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
public static class ChainExt
{
public static Chainable<T> Chain<T>(this T value) where T : IComparable<T>
{
return new Chainable<T>(value);
}
}
Problem
I want to create a ternary operator for a < b < c which is a < b && b < c. or any other option you can think of that a < b > c and so on... I am a fan of my own shortform and I have wanted to create that since I learned programming in high school. How?