Skip to content

Instantly share code, notes, and snippets.

@TrevorVonSeggern
Last active October 17, 2018 03:24
Show Gist options
  • Save TrevorVonSeggern/4471de18e244c50d7b772bdc15be4826 to your computer and use it in GitHub Desktop.
Save TrevorVonSeggern/4471de18e244c50d7b772bdc15be4826 to your computer and use it in GitHub Desktop.
C# Operator Overloading
using System;
public class Program
{
public static void Main()
{
var a = new Thing();
var b = new Thing();
Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);
Console.WriteLine(a[2]);
Console.WriteLine(a[2] = b);
Console.WriteLine(a++);
Console.WriteLine(a--);
}
public class Thing {
public int Value = 5;
public override string ToString()
{
return Value.ToString();
}
public static Thing operator+ (Thing left, Thing right)
{
var result = new Thing();
result.Value = left.Value + right.Value;
return result;
}
public static Thing operator- (Thing left, Thing right)
{
var result = new Thing();
result.Value = left.Value - right.Value;
return result;
}
public static Thing operator* (Thing left, Thing right)
{
var result = new Thing();
result.Value = left.Value * right.Value;
return result;
}
public static Thing operator/ (Thing left, Thing right)
{
var result = new Thing();
result.Value = left.Value / right.Value;
return result;
}
public static Thing operator% (Thing left, Thing right)
{
var result = new Thing();
result.Value = left.Value % right.Value;
return result;
}
public Thing this[int i]
{
get { Value = i; return this; }
set { this.Value = value.Value; }
}
public static Thing operator++ (Thing thing)
{
thing.Value = thing.Value + 1;
return thing;
}
public static Thing operator-- (Thing thing)
{
thing.Value = thing.Value - 1;
return thing;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment