Last active
October 17, 2018 03:24
-
-
Save TrevorVonSeggern/4471de18e244c50d7b772bdc15be4826 to your computer and use it in GitHub Desktop.
C# Operator Overloading
This file contains hidden or 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; | |
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