CSharp examples for Custom Type:Operator Overloading
Create two overridden addition operators
using System;//from w ww . jav a 2s.c o m using System.Collections.Generic; using System.Linq; using System.Text; using System.Dynamic; public class MyString { public string Text { get; set; } public static string operator +(MyString w1, MyString w2) { return w1.Text + " " + w2.Text; } public static MyString operator +(MyString w, int i) { return new MyString() { Text = w.Text + i.ToString()}; } public override string ToString() { return Text; } } class MainClass { static void Main(string[] args) { // create two word instances MyString word1 = new MyString() { Text = "Hello" }; MyString word2 = new MyString() { Text = "World" }; // print out the values Console.WriteLine("MyString1: {0}", word1); Console.WriteLine("MyString2: {0}", word2); Console.WriteLine("Added together: {0}", word1 + word2); Console.WriteLine("Added with int: {0}", word1 + 7); } }