/// <summary> /// Parses a complex number string into a <see cref="ComplexNumber"/> object. /// </summary> /// <param name="statement"> /// The statement to parse. /// </param> /// <returns> /// The <see cref="ComplexNumber"/> parsed from the string. Null if parsing failed. /// </returns> public static ComplexNumber Parse(string statement) { const string pattern = @"(^([-]?[\d]+))?(([+-]+)([\d]+)?i)?"; if (Regex.IsMatch(statement, pattern)) { var number = new ComplexNumber(); var matches = Regex.Match(statement, pattern); if (matches.Groups.Count != 0) { // imaginary part is present if (matches.Groups.Count > 2) { // imaginary operator var imSign = matches.Groups[4].Value; if (matches.Groups.Count > 5) { // imaginary part double imPart; if (!double.TryParse(matches.Groups[5].Value, out imPart)) { return null; } number.Im = imPart; } else { number.Im = 1; } if (imSign == "-") { number.Im *= -1; } } // real part double rePart; if (!double.TryParse(matches.Groups[1].Value, out rePart)) { return null; } number.Re = rePart; return number; } } return null; }
/// <summary> /// Tries to parse the statement to a <see cref="ComplexNumber"/> /// </summary> /// <param name="statement"> /// The statement to parse. /// </param> /// <param name="complexNumber"> /// The <see cref="ComplexNumber"/> parsed from the string. A new one if parsing failed. /// </param> /// <returns> /// True if parse succeeded and false otherwise. /// </returns> public static bool TryParse(string statement, out ComplexNumber complexNumber) { var parsedNumber = Parse(statement); if (parsedNumber == null) { complexNumber = new ComplexNumber(); return false; } complexNumber = parsedNumber; return true; }
/// <summary> /// Returns the Equality when the type is correct. /// </summary> /// <param name="other"> /// The other object. /// </param> /// <returns> /// The <see cref="bool"/> indicating equality. /// </returns> protected bool Equals(ComplexNumber other) { return this.Re.Equals(other.Re) && this.Im.Equals(other.Im); }
/// <summary> /// Returns the Equality when the type is correct. /// </summary> /// <param name="other"> /// The other object. /// </param> /// <returns> /// The <see cref="bool"/> indicating equality. /// </returns> protected bool Equals(ComplexNumber other) { return(this.Re.Equals(other.Re) && this.Im.Equals(other.Im)); }