IntroductionThis small example demonstrates using some of the interesting language elements of the C# language. Probably the most interesting is operator overloading - a feature that shouldn't be overused, but in this example the using is appropriate. Further an override of the ToString() method and attribute using are demonstrated as well. The attribute [Description] is used instead of simple comments, which can be used when referencing the component.Source Code namespace PROINFO.Math.Complex{using System;using System.ComponentModel;using System.Diagnostics; public class Complex{[Description("Constructor")]public Complex(double re, double im){this.re = re;this.im = im;}[Description("Overloaded binary + operator")]public static Complex operator +(Complex arg1, Complex arg2){return (new Complex(arg1.re + arg2.re, arg1.im + arg2.im));}[Description("Overloaded unary - operator")]public static Complex operator -(Complex arg1){return (new Complex(-arg1.re, -arg1.im));}[Description("Overloaded binary - operator")]public static Complex operator -(Complex arg1, Complex arg2){return (new Complex(arg1.re - arg2.re, arg1.im - arg2.im));}[Description("Overloaded binary * operator")]public static Complex operator *(Complex arg1, Complex arg2){return (new Complex(arg1.re * arg2.re - arg1.im * arg2.im, arg1.re * arg2.im + arg2.re * arg1.im));}[Description("Overloaded binary / operator")]public static Complex operator /(Complex arg1, Complex arg2){double c1, c2, d;d = arg2.re * arg2.re + arg2.im * arg2.im;if (d == 0){return (new Complex(0, 0));}c1 = arg1.re * arg2.re + arg1.im * arg2.im;c2 = arg1.im * arg2.re - arg1.re * arg2.im;return (new Complex(c1 / d, c2 / d));}[Description("Absolute value of a complex number. Usage: c.Abs()")]public double Abs(){return (Math.Sqrt(re * re + im * im));}[Description("Argument of a complex number in degree. Usage: c.Arg()")]public double Arg(){double ret = 0;if (re != 0)ret = (180 / Math.PI) * Math.Atan(im / re);return (ret);}[Description("Overridden ToString. Usage: c.toString()")]public override string ToString(){return (String.Format("Complex: ({0}, {1})", re, im));}// private membersprivate double re;private double im;}public class Test{public static void Main(){Complex c1 = new Complex(3, 3);Complex c2 = new Complex(2, 4);Complex c3 = new Complex(0, 0);Debug.WriteLine(c1 + c2);Debug.WriteLine(c1 - c2);Debug.WriteLine(c1 * c2);Debug.WriteLine(c1 / c2);Debug.WriteLine(c1 + c3);Debug.WriteLine(c1 - c3);Debug.WriteLine(c1 * c3);Debug.WriteLine(c1 / c3);Debug.WriteLine(c1.Abs());Debug.WriteLine(c1.Arg());Debug.WriteLine(c2.Abs());Debug.WriteLine(c2.Arg());Debug.WriteLine(c3.Abs());Debug.WriteLine(c3.Arg());}}}
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: