Nullable bool Types

   
  
using System;
using System.Collections.Generic;
using System.Text;

class DatabaseReader {
    // Nullable data field.
    public int? numbericValue;
    public bool? boolValue = true;

    // Note the nullable return type. 
    public int? GetIntFromDatabase() { return numbericValue; }

    // Note the nullable return type. 
    public bool? GetBoolFromDatabase() { return boolValue; }
}

class Program {
    static void Main(string[] args) {
        DatabaseReader dr = new DatabaseReader();

        int? i = dr.GetIntFromDatabase();
        if (i.HasValue)
            Console.WriteLine("Value of 'i' is: {0}", i);
        else
            Console.WriteLine("Value of 'i' is undefined.");
        // Get bool from 'database'.
        bool? b = dr.GetBoolFromDatabase();
        if (b != null)
            Console.WriteLine("Value of 'b' is: {0}", b);
        else
            Console.WriteLine("Value of 'b' is undefined.");
        // If the value from GetIntFromDatabase() is null, 
        // assign local variable to 100.
        int? myData = dr.GetIntFromDatabase() ?? 100;
        Console.WriteLine("Value of myData: {0}", myData);
    }
}

   
     


Nullable variable

using System;
using System.Collections.Generic;
using System.Text;

public class Vector {
public double? R = null;
public double? Theta = null;

public double? ThetaRadians {
get {
return (Theta * Math.PI / 180.0);
}
}

public Vector(double? r, double? theta) {
if (r < 0) { r = -r; theta += 180; } theta = theta % 360; R = r; Theta = theta; } public static Vector operator +(Vector op1, Vector op2) { try { double newX = op1.R.Value * Math.Sin(op1.ThetaRadians.Value) + op2.R.Value * Math.Sin(op2.ThetaRadians.Value); double newY = op1.R.Value * Math.Cos(op1.ThetaRadians.Value) + op2.R.Value * Math.Cos(op2.ThetaRadians.Value); double newR = Math.Sqrt(newX * newX + newY * newY); double newTheta = Math.Atan2(newX, newY) * 180.0 / Math.PI; return new Vector(newR, newTheta); } catch { return new Vector(null, null); } } public static Vector operator -(Vector op1) { return new Vector(-op1.R, op1.Theta); } public static Vector operator -(Vector op1, Vector op2) { return op1 + (-op2); } public override string ToString() { string rString = R.HasValue ? R.ToString() : "null"; string thetaString = Theta.HasValue ? Theta.ToString() : "null"; return string.Format("({0}, {1})", rString, thetaString); } } class Program { public static void Main(string[] args) { Vector v1 = GetVector("vector1"); Vector v2 = GetVector("vector1"); Console.WriteLine("{0} + {1} = {2}", v1, v2, v1 + v2); Console.WriteLine("{0} - {1} = {2}", v1, v2, v1 - v2); Console.ReadKey(); } public static Vector GetVector(string name) { Console.WriteLine("Input {0} magnitude:", name); double? r = GetNullableDouble(); Console.WriteLine("Input {0} angle (in degrees):", name); double? theta = GetNullableDouble(); return new Vector(r, theta); } public static double? GetNullableDouble() { double? result; string userInput = Console.ReadLine(); try { result = double.Parse(userInput); } catch { result = null; } return result; } } [/csharp]

Matrix 3 x 3

   
 
//http://isotopescreencapture.codeplex.com/
//The MIT License (MIT)
namespace Isotope.Math
{
    public struct Matrix3x3
    {
        public double M11, M12, M13;
        public double M21, M22, M23;
        public double M31, M32, M33;

        public Matrix3x3(
            double m11,
            double m12,
            double m13,
            double m21,
            double m22,
            double m23,
            double m31,
            double m32,
            double m33)
        {
            M11 = m11;
            M12 = m12;
            M13 = m13;
            M21 = m21;
            M22 = m22;
            M23 = m23;
            M31 = m31;
            M32 = m32;
            M33 = m33;
        }

        public Matrix3x3 Multiply(Matrix3x3 m)
        {
            var result = new Matrix3x3();

            result.M11 = this.M11*m.M11 + this.M12*m.M21 + this.M13*m.M31;
            result.M12 = this.M11*m.M12 + this.M12*m.M22 + this.M13*m.M32;
            result.M13 = this.M11*m.M13 + this.M12*m.M23 + this.M13*m.M33;

            result.M21 = this.M21*m.M11 + this.M22*m.M21 + this.M23*m.M31;
            result.M22 = this.M21*m.M12 + this.M22*m.M22 + this.M23*m.M32;
            result.M23 = this.M21*m.M13 + this.M22*m.M23 + this.M23*m.M33;

            result.M31 = this.M31*m.M11 + this.M32*m.M21 + this.M33*m.M31;
            result.M32 = this.M31*m.M12 + this.M32*m.M22 + this.M33*m.M32;
            result.M33 = this.M31*m.M13 + this.M32*m.M23 + this.M33*m.M33;

            return result;
        }

        public static Matrix3x3 operator *(Matrix3x3 a, Matrix3x3 b)
        {
            return a.Multiply(b);
        }

    }
}

   
     


Matrix used in linear algebra

/*
Copyright (c) 2010 James Craig

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Text;
using System.Xml.Serialization;
#endregion

namespace Utilities.Math
{
///

/// Matrix used in linear algebra
///

[Serializable()]
public class Matrix
{
#region Constructor
///

/// Constructor
///

/// Width of the matrix /// Height of the matrix public Matrix(int Width,int Height)
{
_Width = Width;
_Height = Height;
_Values = new double[Width, Height];
}
#endregion

#region Public Properties
///

/// Width of the matrix
///

[XmlElement]
public int Width
{
get { return _Width; }
set { _Width = value; _Values = new double[Width, Height]; }
}

///

/// Height of the matrix
///

[XmlElement]
public int Height
{
get { return _Height; }
set { _Height = value; _Values = new double[Width, Height]; }
}
///

/// Sets the values of the matrix
///

/// X position /// Y position /// the value at a point in the matrix
public double this[int X, int Y]
{
get
{
if (X < _Width && X >= 0 && Y < _Height && Y >= 0)
{
return _Values[X, Y];
}
throw new Exception(“Index out of bounds”);
}

set
{
if (X < _Width && X >= 0 && Y < _Height && Y >= 0)
{
_Values[X, Y] = value;
return;
}
throw new Exception(“Index out of bounds”);
}
}

///

/// Values for the matrix
///

[XmlElement]
public double[,] Values
{
get { return _Values; }
set { _Values = value; }
}
#endregion

#region Private Variables
private int _Width = 1;
private int _Height = 1;
private double[,] _Values = null;
#endregion

#region Operators
public static bool operator ==(Matrix M1, Matrix M2)
{
if (M1.Width != M2.Width || M1.Height != M2.Height)
return false;
for (int x = 0; x <= M1.Width; ++x) { for (int y = 0; y <= M1.Height; ++y) { if (M1[x, y] != M2[x, y]) return false; } } return true; } public static bool operator !=(Matrix M1, Matrix M2) { return !(M1 == M2); } public static Matrix operator +(Matrix M1, Matrix M2) { if (M1.Width != M2.Width || M1.Height != M2.Height) throw new ArgumentException("Both matrices must be the same dimensions."); Matrix TempMatrix = new Matrix(M1.Width, M1.Height); for (int x = 0; x < M1.Width; ++x) { for (int y = 0; y < M1.Height; ++y) { TempMatrix[x, y] = M1[x, y] + M2[x, y]; } } return TempMatrix; } public static Matrix operator -(Matrix M1, Matrix M2) { if (M1.Width != M2.Width || M1.Height != M2.Height) throw new ArgumentException("Both matrices must be the same dimensions."); Matrix TempMatrix = new Matrix(M1.Width, M1.Height); for (int x = 0; x < M1.Width; ++x) { for (int y = 0; y < M1.Height; ++y) { TempMatrix[x, y] = M1[x, y] - M2[x, y]; } } return TempMatrix; } public static Matrix operator -(Matrix M1) { Matrix TempMatrix = new Matrix(M1.Width, M1.Height); for (int x = 0; x < M1.Width; ++x) { for (int y = 0; y < M1.Height; ++y) { TempMatrix[x, y] = -M1[x, y]; } } return TempMatrix; } public static Matrix operator *(Matrix M1, Matrix M2) { if (M1.Width != M2.Width || M1.Height != M2.Height) throw new ArgumentException("Dimensions for the matrices are incorrect."); Matrix TempMatrix = new Matrix(M2.Width, M1.Height); for (int x = 0; x < M2.Width; ++x) { for (int y = 0; y < M1.Height; ++y) { TempMatrix[x,y]=0.0; for (int i = 0; i < M1.Width; ++i) { for (int j = 0; j < M2.Height; ++j) { TempMatrix[x, y] += (M1[i, y] * M2[x, j]); } } } } return TempMatrix; } public static Matrix operator *(Matrix M1,double D) { Matrix TempMatrix = new Matrix(M1.Width, M1.Height); for (int x = 0; x < M1.Width; ++x) { for (int y = 0; y < M1.Height; ++y) { TempMatrix[x, y] = M1[x, y] * D; } } return TempMatrix; } public static Matrix operator *(double D, Matrix M1) { Matrix TempMatrix = new Matrix(M1.Width, M1.Height); for (int x = 0; x < M1.Width; ++x) { for (int y = 0; y < M1.Height; ++y) { TempMatrix[x, y] = M1[x, y] * D; } } return TempMatrix; } public static Matrix operator /(Matrix M1, double D) { return M1 * (1 / D); } public static Matrix operator /(double D, Matrix M1) { return M1 * (1 / D); } #endregion #region Public Overridden Functions public override bool Equals(object obj) { if (obj is Matrix) { return this == (Matrix)obj; } return false; } public override int GetHashCode() { double Hash=0; for (int x = 0; x < Width; ++x) { for (int y = 0; y < Height; ++y) { Hash += this[x, y]; } } return (int)Hash; } public override string ToString() { StringBuilder Builder = new StringBuilder(); string Seperator = ""; Builder.Append("{" + System.Environment.NewLine); for (int x = 0; x < Width; ++x) { Builder.Append("{"); for (int y = 0; y < Height; ++y) { Builder.Append(Seperator + this[x, y]); Seperator = ","; } Builder.Append("}" + System.Environment.NewLine); Seperator = ""; } Builder.Append("}"); return Builder.ToString(); } #endregion #region Public Functions ///

/// Transposes the matrix
///

/// Returns a new transposed matrix
public Matrix Transpose()
{
Matrix TempValues = new Matrix(Height, Width);
for (int x = 0; x < Width; ++x) { for (int y = 0; y < Height; ++y) { TempValues[y, x] = _Values[x, y]; } } return TempValues; } ///

/// Gets the determinant of a square matrix
///

/// The determinant of a square matrix
public double Determinant()
{
if (Width != Height)
throw new Exception(“The determinant can not be calculated for a non square matrix”);
if (Width == 2)
{
return (this[0, 0] * this[1, 1]) – (this[0, 1] * this[1, 0]);
}
double Answer = 0.0;
for (int x = 0; x < Width; ++x) { Matrix TempMatrix = new Matrix(Width - 1, Height - 1); int WidthCounter = 0; for (int y = 0; y < Width; ++y) { if (y != x) { for (int z = 1; z < Height; ++z) { TempMatrix[WidthCounter, z - 1] = this[y, z]; } ++WidthCounter; } } if (x % 2 == 0) { Answer += TempMatrix.Determinant(); } else { Answer -= TempMatrix.Determinant(); } } return Answer; } #endregion } } [/csharp]

Matrix class

//http://calcsharp.codeplex.com/license
//Microsoft Public License (Ms-PL)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing;

namespace CalcSharp.Core.Containers
{
[Serializable]
public abstract class AMatrix : IFormattable, ICloneable, IEquatable
{
private int nRows, nCols;

protected AMatrix(int rows, int columns)
{
if (rows < 1) throw new ArgumentException("must be greater than 0", "rows"); if (columns < 1) throw new ArgumentException("must be greater than 0", "columns"); nRows = rows; nCols = columns; } #region Properties public virtual double this[int row, int column] { get { RangeCheck(row, column); return ValueAt(row, column); } set { RangeCheck(row, column); ValueAt(row, column, value); } } public int Columns { get { return nCols; } protected set { nCols = value; } } public int Rows { get { return nRows; } protected set { nRows = value; } } #endregion #region Interface Implementations public override bool Equals(object obj) { return Equals(obj as AMatrix); } public bool Equals(AMatrix other) { // Reject equality when the argument is null or has a different shape. if (other == null) { return false; } if (Columns != other.Columns || Rows != other.Rows) { return false; } // Accept if the argument is the same object as this. if (ReferenceEquals(this, other)) { return true; } // If all else fails, perform elementwise comparison. for (int i = 0; i < Rows; i++) { for (int j = 0; j < Columns; j++) { if (ValueAt(i, j) != other.ValueAt(i, j)) { return false; } } } return true; } public override int GetHashCode() { int hashNum = System.Math.Max(Rows * Columns, 25); double[] hashBase = new double[hashNum]; for (int i = 0; i < hashNum; i++) { int col = i % Columns; int row = (i - col) / Rows; hashBase[i] = this[row, col]; } return hashBase.GetHashCode(); } object ICloneable.Clone() { return Clone(); } public virtual AMatrix Clone() { AMatrix result = CreateMatrix(Rows, Columns); CopyTo(result); return result; } public virtual string ToString(string format, IFormatProvider formatProvider) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Rows; i++) { for (int j = 0; j < Columns; j++) { sb.Append(ValueAt(i, j).ToString(format, formatProvider)); if (j != Columns - 1) { sb.Append(", "); } } if (i != Rows - 1) { sb.Append(Environment.NewLine); } } return sb.ToString(); } #endregion private void RangeCheck(int row, int column) { if (row < 0 || row >= nRows) throw new ArgumentOutOfRangeException(“row”);
if (column < 0 || column >= nCols) throw new ArgumentOutOfRangeException(“column”);
}

public virtual void CopyTo(AMatrix target)
{
if (target == null) throw new ArgumentNullException(“target”);
if (Rows != target.Rows || Columns != target.Columns) throw new Exception(“Target & Source rows/column count mismatch”);

for (int i = 0; i < this.nRows; i++) { for (int j = 0; j < this.nCols; j++) { target.ValueAt(i, j, this.ValueAt(i, j)); } } } public void Negate() { for (int i = 0; i < Rows; i++) { for (int j = 0; j < Columns; j++) { this.ValueAt(i, j, -1*this.ValueAt(i, j)); } } } #region Abstract parts protected internal abstract void ValueAt(int row, int column, double value); protected internal abstract double ValueAt(int row, int column); protected internal abstract AMatrix CreateMatrix(int numberOfRows, int numberOfColumns); public abstract double Determinant(); public abstract AMatrix Transpose(); public abstract AMatrix Inverse(); public abstract void Clear(); public abstract double[] GetRow(int index); public abstract double[] GetColumn(int index); public abstract void SetColumn(int index, double[] source); public abstract void SetRow(int index, double[] source); public abstract Bitmap GetPreview(); #endregion } } [/csharp]

Inverts a Matrix

   
 

//-----------------------------------------------------------------------
// <copyright file="Extensions.cs" company="Microsoft Corporation copyright 2008.">
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
// </copyright>
// <date>26-Feb-2009</date>
// <summary>Extensions class.</summary>
//-----------------------------------------------------------------------
namespace Blacklight.Controls
{
    using System;
    using System.Windows;
    using System.Windows.Media;

    /// <summary>
    /// This set of internal extension methods provide general solutions and 
    /// utilities in a small enough number to not warrant a dedicated extension
    /// methods class.
    /// </summary>
    internal static partial class Extensions
    {
        /// <summary>
        /// Inverts a Matrix. The Invert functionality on the Matrix type is 
        /// internal to the framework only. Since Matrix is a struct, an out 
        /// parameter must be presented.
        /// </summary>
        /// <param name="m">The Matrix object.</param>
        /// <param name="outputMatrix">The matrix to return by an output 
        /// parameter.</param>
        /// <returns>Returns a value indicating whether the type was 
        /// successfully inverted. If the determinant is 0.0, then it cannot 
        /// be inverted and the original instance will remain untouched.</returns>
        public static bool Invert(this Matrix m, out Matrix outputMatrix)
        {
            double determinant = m.M11 * m.M22 - m.M12 * m.M21;
            if (determinant == 0.0)
            {
                outputMatrix = m;
                return false;
            }

            Matrix matCopy = m;
            m.M11 = matCopy.M22 / determinant;
            m.M12 = -1 * matCopy.M12 / determinant;
            m.M21 = -1 * matCopy.M21 / determinant;
            m.M22 = matCopy.M11 / determinant;
            m.OffsetX = (matCopy.OffsetY * matCopy.M21 - matCopy.OffsetX * matCopy.M22) / determinant;
            m.OffsetY = (matCopy.OffsetX * matCopy.M12 - matCopy.OffsetY * matCopy.M11) / determinant;

            outputMatrix = m;
            return true;
        }

        /// <summary>
        /// An implementation of the Contains member of string that takes in a 
        /// string comparison. The traditional .NET string Contains member uses 
        /// StringComparison.Ordinal.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <param name="value">The string value to search for.</param>
        /// <param name="comparison">The string comparison type.</param>
        /// <returns>Returns true when the substring is found.</returns>
        public static bool Contains(this string s, string value, StringComparison comparison)
        {
            return s.IndexOf(value, comparison) >= 0;
        }
    }
}