Sparse Double Range

   
 
//http://isotopescreencapture.codeplex.com/
//The MIT License (MIT)
using System.Collections.Generic;
using System.Linq;

namespace Isotope.Collections.Ranges
{
    public static partial class EnumerableUtil
    {
        public static IEnumerable<T> Single<T>(T item)
        {
            yield return item;
        }




        /// <summary>
        /// Given a range (start,end) and a number of steps, will yield that a number for each step
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="steps"></param>
        /// <returns></returns>
        public static IEnumerable<double> RangeSteps(double start, double end, int steps)
        {
            // for non-positive number of steps, yield no points
            if (steps < 1)
            {
                yield break;
            }

            // for exactly 1 step, yield the start value
            if (steps == 1)
            {
                yield return start;
                yield break;
            }

            // for exactly 2 stesp, yield the start value, and then the end value
            if (steps == 2)
            {
                yield return start;
                yield return end;
                yield break;
            }

            // for 3 steps or above, start yielding the segments
            // notice that the start and end values are explicitly returned so that there
            // is no possibility of rounding error affecting their values
            int segments = steps - 1;
            double total_length = end - start;
            double stepsize = total_length / segments;
            yield return start;
            for (int i = 1; i < (steps - 1); i++)
            {
                double p = start + (stepsize * i);
                yield return p;
            }
            yield return end;
        }

        public static IEnumerable<TGROUP> GroupByCount<T, TGROUP>(
            IEnumerable<T> items,
            int group_size,
            System.Func<int, TGROUP> func_new_col,
            System.Action<TGROUP, int, T> func_add) where TGROUP : class
        {


            if (items == null)
            {
                throw new System.ArgumentNullException("items");
            }

            if (group_size < 1)
            {
                throw new System.ArgumentOutOfRangeException("group_size");
            }

            if (func_new_col == null)
            {
                throw new System.ArgumentNullException("func_new_col");
            }


            if (func_add == null)
            {
                throw new System.ArgumentNullException("func_add");
            }



            int cur_group_size = 0;
            TGROUP cur_group = null;
            foreach (var item in items)
            {
                if (cur_group_size == 0)
                {
                    if (cur_group == null)
                    {
                        cur_group = func_new_col(group_size);
                    }
                    else
                    {
                        throw new System.InvalidOperationException();
                    }
                }

                func_add(cur_group, cur_group_size, item);
                cur_group_size++;
                if (cur_group_size == group_size)
                {

                    yield return cur_group;
                    cur_group = null;
                    cur_group_size = 0;
                }

            }

            if (cur_group_size > 0)
            {
                if (cur_group == null)
                {
                    throw new System.InvalidOperationException();
                }
                yield return cur_group;
            }

        }

        public static IEnumerable<TGROUP> GroupByCount<T, TGROUP>(ICollection<T> items, ICollection<int> group_sizes, System.Func<int, TGROUP> func_new_col, System.Action<TGROUP, int, T> func_add)
        {


            if (items == null)
            {
                throw new System.ArgumentNullException("items");
            }

            if (group_sizes == null)
            {
                throw new System.ArgumentNullException("group_sizes");
            }

            if (func_new_col == null)
            {
                throw new System.ArgumentNullException("func_new_col");
            }


            if (func_add == null)
            {
                throw new System.ArgumentNullException("func_add");
            }



            int total_group_sizes = group_sizes.Sum();
            if (total_group_sizes != items.Count)
            {
                throw new System.ArgumentException("group_sizes must account for all items");
            }

            int items_added = 0;
            for (int group_index = 0; group_index < group_sizes.Count; group_index++)
            {
                int cur_group_size = group_sizes.ElementAt(group_index);

                if (cur_group_size < 0)
                {
                    throw new System.ArgumentException("group_sizes contains a negative numver");
                }
                var cur_group = func_new_col(cur_group_size);
                for (int row_index = 0; row_index < cur_group_size; row_index++)
                {
                    var cur_item = items.ElementAt(items_added);
                    func_add(cur_group, row_index, cur_item);
                    items_added++;
                }
                yield return cur_group;

            }

        }


        public static IDictionary<K, List<V>> Bucketize<K, V>(IEnumerable<V> items, System.Func<V, K> func_get_key, IEqualityComparer<K> ieq)
        {
            if (items == null)
            {
                throw new System.ArgumentNullException("items");
            }

            if (func_get_key == null)
            {
                throw new System.ArgumentNullException("func_get_key");
            }

            var dic = new Dictionary<K, List<V>>(ieq);
            foreach (var item in items)
            {
                var key = func_get_key(item);
                List<V> list = null;
                bool found = dic.TryGetValue(key, out list);
                if (!found)
                {
                    list = new List<V>();
                    dic[key] = list;
                }
                list.Add(item);

            }

            return dic;
        }


        public static IDictionary<K, List<V>> Bucketize<K, V>(IEnumerable<V> items, System.Func<V, K> func_get_key)
        {
            IEqualityComparer<K> ieq = null;
            return Bucketize<K, V>(items, func_get_key, ieq);
        }


        public static IDictionary<K, int> Histogram<K, V>(IEnumerable<V> items, System.Func<V, K> func_get_key, IEqualityComparer<K> ieq)
        {
            if (items == null)
            {
                throw new System.ArgumentNullException("items");
            }

            if (func_get_key == null)
            {
                throw new System.ArgumentNullException("func_get_key");
            }

            var dic = new Dictionary<K, int>(ieq);
            foreach (var item in items)
            {
                var key = func_get_key(item);
                int old_value = 0;
                bool found = dic.TryGetValue(key, out old_value);
                if (!found)
                {
                    dic[key] = 1;
                }
                else
                {
                    dic[key] = old_value + 1;
                }

            }

            return dic;
        }

        public static IDictionary<T, int> Histogram<T>(IEnumerable<T> items)
        {
            var dic = Histogram(items, i => i, null);
            return dic;
        }

        public static List<List<T>> Chunkify<T>(IEnumerable<T> items, int chunksize)
        {
            var chunks = new List<List<T>>();
            List<T> cur_chunk = null;
            Chunkify(items, chunksize,
                () =>
                {
                    cur_chunk = new List<T>(chunksize); chunks.Add(cur_chunk);
                },
                item =>
                {
                    cur_chunk.Add(item);
                });

            return chunks;
        }

        public static void Chunkify<T>(IEnumerable<T> items, int chunksize, System.Action create_chunk, System.Action<T> add_item)
        {
            if (items == null)
            {
                throw new System.ArgumentNullException("items");
            }

            if (chunksize < 1)
            {
                throw new System.ArgumentOutOfRangeException("chunksize");
            }

            int item_count = 0;
            int curchunk_size = 0;
            foreach (T item in items)
            {
                if ((item_count % chunksize) == 0)
                {
                    create_chunk();
                    curchunk_size = 0;
                }
                add_item(item);
                item_count++;
                curchunk_size++;
            }

        }
    }
    public struct DoubleRange
    {
        public readonly double _Lower;
        public readonly double _Upper;

        public double Lower
        {
            get { return this._Lower; }
        }

        public double Upper
        {
            get { return this._Upper; }
        }

        private DoubleRange(double lower, double upper)
        {
            this._Lower = lower;
            this._Upper = upper;
        }

        /// <summary>
        /// Creates a range from the lower and upper values
        /// </summary>
        /// <example>
        /// (0,0) -> [0]
        /// (0,1) -> [0,1]
        /// (0,5) -> [0,1,2,3,4,5]
        /// (2,5) -> [2,3,4,5]
        /// </example>
        /// <param name="lower"></param>
        /// <param name="upper"></param>
        /// <returns></returns>
        public static DoubleRange FromEndpoints(double lower, double upper)
        {
            return new DoubleRange(lower, upper);
        }

        public double Length
        {
            get { return this.Upper - this.Lower; }
        }

        public override string ToString()
        {
            var invariant_culture = System.Globalization.CultureInfo.InvariantCulture;
            return string.Format(invariant_culture, "Range({0},{1})", this.Lower, this.Upper);
        }

        private static bool _intersects_exclusive(DoubleRange range1, DoubleRange range2)
        {
            bool val = (range1.Lower < range2.Lower) &amp;&amp; (range1.Upper > range2.Lower);
            return val;
        }

        private static bool _intersects_inclusive(DoubleRange range1, DoubleRange range2)
        {
            bool val = (range1.Lower <= range2.Lower) &amp;&amp; (range1.Upper >= range2.Upper);
            return val;
        }

        /// <summary>
        /// Tests if this range interests with another
        /// </summary>
        /// <param name="range">the other range</param>
        /// <returns>true if they intersect</returns>
        public bool IntersectsExclusive(DoubleRange range)
        {
            bool val = _intersects_exclusive(this, range) || _intersects_exclusive(range, this);
            return val;
        }

        public bool IntersectsInclusive(DoubleRange range)
        {
            bool val = _intersects_inclusive(this, range) || _intersects_inclusive(range, this);
            return val;
        }

        private static bool _touches(DoubleRange range1, DoubleRange range2)
        {
            var val = (range1.Upper == range2.Lower);
            return val;
        }

        /// <summary>
        /// Tests if this range touches another. For example (1-2) touches (3,5) but (1,2) does not touch (4,5)
        /// </summary>
        /// <param name="range">the other range</param>
        /// <returns>true if they touch</returns>
        public bool Touches(DoubleRange range)
        {
            var val = _touches(this, range) || _touches(range, this);
            return val;
        }

        /// <summary>
        /// Tests if this range contains a specific double
        /// </summary>
        /// <param name="n">the double</param>
        /// <returns>true if the number is contained</returns>
        public bool Contains(double n)
        {
            return (this.Lower <= n) &amp;&amp; (n <= this.Upper);
        }

        /// <summary>
        /// Join this range with another and return a single range that contains them both. The ranges must either touch or interest.
        /// for example (0,2) amd (3,7) will yield (0,7)
        /// </summary>
        /// <param name="range">the other range</param>
        /// <returns>the merged range</returns>
        public DoubleRange JoinWith(DoubleRange range)
        {
            if (this.IntersectsExclusive(range) || this.Touches(range))
            {
                double new_Upper = System.Math.Max(this.Upper, range.Upper);
                double new_Lower = System.Math.Min(this.Lower, range.Lower);
                return DoubleRange.FromEndpoints(new_Lower, new_Upper);
            }
            else
            {
                throw new System.ArgumentException("Ranges cannot be joined because they do not touch or overlap");
            }
        }

        public IEnumerable<double> Values
        {
            get
            {
                double step = 1.0;
                return this.GetValues(step);
            }
        }

        public IEnumerable<double> GetValues(double step)
        {
            if (step <= 0.0)
            {
                throw new System.ArgumentOutOfRangeException("step", "must be positive");
            }

            double i = this.Lower;
            while (i <= this.Upper)
            {
                yield return i;
                i += step;
            }
        }
    }

    public class SparseDoubleRange
    {
        private List<DoubleRange> ranges;

        public SparseDoubleRange()
        {
            this.clear();
        }

        public IEnumerable<DoubleRange> Ranges
        {
            get
            {
                foreach (var range in this.ranges)
                {
                    yield return range;
                }
            }
        }

        public double Count
        {
            get
            {
                double length = this.ranges.Aggregate(0.0, (old, rng) => old + rng.Length);
                return length;
            }
        }

        private void clear()
        {
            this.ranges = new List<DoubleRange>();
        }

        public int RangeCount
        {
            get { return this.ranges.Count; }
        }

        public void AddInclusive(double lower, double upper)
        {
            var rng = DoubleRange.FromEndpoints(lower, upper);
            this.Add(rng);
        }

        public void Add(DoubleRange range)
        {
            var left = new List<DoubleRange>();
            var right = new List<DoubleRange>();
            foreach (var rng in this.ranges)
            {
                if (range.IntersectsExclusive(rng) || range.Touches(rng))
                {
                    range = range.JoinWith(rng);
                }
                else if (rng.Upper < range.Lower)
                {
                    left.Add(rng);
                }
                else if (range.Upper < rng.Lower)
                {
                    right.Add(rng);
                }
                else
                {
                    throw new System.InvalidOperationException("Internal Error");
                }
            }

            this.ranges = left.Concat(EnumerableUtil.Single(range)).Concat(right).ToList();
        }

        public double Lower
        {
            get
            {
                if (this.ranges.Count < 1)
                {
                    throw new System.InvalidOperationException("empty");
                }

                return this.ranges&#91;0&#93;.Lower;
            }
        }

        public double Upper
        {
            get
            {
                if (this.ranges.Count < 1)
                {
                    throw new System.InvalidOperationException("empty");
                }

                return this.ranges&#91;this.ranges.Count - 1&#93;.Upper;
            }
        }

        public void RemoveInclusive(int lower, int upper)
        {
            var rng = DoubleRange.FromEndpoints(lower, upper);
            this.RemoveInclusive(rng);
        }

        public void RemoveExclusive(int lower, int upper)
        {
            if ((upper - lower) > (2 * double.Epsilon))
            {
                var rng = DoubleRange.FromEndpoints(lower + double.Epsilon, upper - double.Epsilon);
                this.RemoveInclusive(rng);
            }
        }

        public void RemoveInclusive(DoubleRange range)
        {
            // if the range doesn&#039;t intersect this collection do nothing
            if (!range.IntersectsInclusive(DoubleRange.FromEndpoints(this.Lower, this.Upper)))
            {
                return;
            }

            var middle = new List<DoubleRange>();

            foreach (var S in this.ranges)
            {
                if (!range.IntersectsInclusive(S))
                {
                    middle.Add(S);
                    continue;
                }

                if ((range.Lower <= S.Lower) &amp;&amp; (range.Upper >= S.Upper))
                {
                    // disregard S completely
                    continue;
                }

                if (range.Lower > S.Lower)
                {
                    if (S.Lower <= (range.Lower - double.Epsilon))
                    {
                        var X = DoubleRange.FromEndpoints(S.Lower, range.Lower);
                        middle.Add(X);
                    }
                }

                if (range.Upper <= S.Upper)
                {
                    if ((range.Upper + double.Epsilon) <= S.Upper)
                    {
                        var X = DoubleRange.FromEndpoints(range.Upper, S.Upper);
                        middle.Add(X);
                    }
                }
                else
                {
                    throw new System.InvalidOperationException("internal error");
                }
            }

            this.ranges = middle;
        }

        public DoubleRange? FindRangeContainingNumber(double n)
        {
            foreach (var rng in this.ranges)
            {
                if (rng.Contains(n))
                {
                    return rng;
                }
            }

            return null;
        }

        public bool Contains(double n)
        {
            var rng = this.FindRangeContainingNumber(n);
            return rng != null ? true : false;
        }

        public override string ToString()
        {
            var sb = new System.Text.StringBuilder();
            sb.AppendFormat("{0}(", this.GetType().Name);
            foreach (var rng in this.ranges)
            {
                sb.Append(rng.ToString());
            }

            sb.Append(")");
            return sb.ToString();
        }

        public IEnumerable<double> Values
        {
            get
            {
                foreach (var rng in this.Ranges)
                {
                    foreach (int i in rng.Values)
                    {
                        yield return i;
                    }
                }
            }
        }

        public IEnumerable<double> GetValues(double step)
        {
            foreach (var rng in this.Ranges)
            {
                foreach (double i in rng.GetValues(step))
                {
                    yield return i;
                }
            }
        }
    }
}

   
     


Int Range

//http://isotopescreencapture.codeplex.com/
//The MIT License (MIT)
using System.Collections.Generic;

namespace Isotope.Collections.Ranges
{
public struct IntRange
{
public readonly int _Lower;
public readonly int _Length;

public int Lower
{
get { return this._Lower; }
}

public int Upper
{
get { return this.Lower + this.Length – 1; }
}

public int Length
{
get { return this._Length; }
}

private IntRange(int lower, int length)
{
this._Lower = lower;
this._Length = length;

if (this.Lower > this.Upper)
{
throw new System.OverflowException();
}
}

///

/// Creates a range from the lower and upper values
///

///
/// (0,0) -> [0]
/// (0,1) -> [0,1]
/// (0,5) -> [0,1,2,3,4,5]
/// (2,5) -> [2,3,4,5]
///

/// /// ///
public static IntRange FromEndpoints(int lower, int upper)
{
return new IntRange(lower, upper – lower + 1);
}

///

/// Creates a range of a single number
///

///
///
///
public static IntRange FromInteger(int value)
{
return new IntRange(value, 1);
}

///

/// Creates a new range from a starting value and including all the numbers following that
///

///
/// (2,0) -> []
/// (2,1) -> [2]
/// (2,2) -> [2,3]
/// (2,3) -> [2,3,4]
/// (2,4) -> [2,3,4,5]
///

/// /// ///
public static IntRange FromLower(int lower, int length)
{
if (length < 0) { throw new System.ArgumentOutOfRangeException("length", "must be >= 0″);
}

return new IntRange(lower, length);
}

public override string ToString()
{
var invariant_culture = System.Globalization.CultureInfo.InvariantCulture;
return string.Format(invariant_culture, “Range({0},{1})”, this.Lower, this.Upper);
}

private static bool _intersects(IntRange range1, IntRange range2)
{
return ((range1.Lower <= range2.Lower) && (range1.Upper >= range2.Lower));
}

///

/// Tests if this range interests with another
///

/// the other range /// true if they intersect
public bool Intersects(IntRange range)
{
return (_intersects(this, range) || _intersects(range, this));
}

private static int Delta = 1;

private static bool _touches(IntRange range1, IntRange range2)
{
var val = (range1.Upper + Delta) == range2.Lower;
return val;
}

///

/// Tests if this range touches another. For example (1-2) touches (3,5) but (1,2) does not touch (4,5)
///

/// the other range /// true if they touch
public bool Touches(IntRange range)
{
var val = _touches(this, range) || _touches(range, this);
return val;
}

///

/// Tests if this range contains a specific integer
///

/// the integet /// true if the number is contained
public bool Contains(int n)
{
return ((this.Lower <= n) && (n <= this.Upper)); } ///

/// Join this range with another and return a single range that contains them both. The ranges must either touch or interest.
/// for example (0,2) amd (3,7) will yield (0,7)
///

/// the other range /// the merged range
public IntRange JoinWith(IntRange range)
{
if (this.Intersects(range) || this.Touches(range))
{
int new_Upper = System.Math.Max(this.Upper, range.Upper);
int new_Lower = System.Math.Min(this.Lower, range.Lower);
return IntRange.FromEndpoints(new_Lower, new_Upper);
}
else
{
throw new System.ArgumentException();
}
}

///

/// Get each int int he range from the lower value to the upper value
///

/// each int in the range
public IEnumerable Values
{
get
{
for (int i = this.Lower; i <= this.Upper; i++) { yield return i; } } } } } [/csharp]

Double Range

//http://isotopescreencapture.codeplex.com/
//The MIT License (MIT)
using System.Collections.Generic;

namespace Isotope.Collections.Ranges
{
public struct DoubleRange
{
public readonly double _Lower;
public readonly double _Upper;

public double Lower
{
get { return this._Lower; }
}

public double Upper
{
get { return this._Upper; }
}

private DoubleRange(double lower, double upper)
{
this._Lower = lower;
this._Upper = upper;
}

///

/// Creates a range from the lower and upper values
///

///
/// (0,0) -> [0]
/// (0,1) -> [0,1]
/// (0,5) -> [0,1,2,3,4,5]
/// (2,5) -> [2,3,4,5]
///

/// /// ///
public static DoubleRange FromEndpoints(double lower, double upper)
{
return new DoubleRange(lower, upper);
}

public double Length
{
get { return this.Upper – this.Lower; }
}

public override string ToString()
{
var invariant_culture = System.Globalization.CultureInfo.InvariantCulture;
return string.Format(invariant_culture, “Range({0},{1})”, this.Lower, this.Upper);
}

private static bool _intersects_exclusive(DoubleRange range1, DoubleRange range2)
{
bool val = (range1.Lower < range2.Lower) && (range1.Upper > range2.Lower);
return val;
}

private static bool _intersects_inclusive(DoubleRange range1, DoubleRange range2)
{
bool val = (range1.Lower <= range2.Lower) && (range1.Upper >= range2.Upper);
return val;
}

///

/// Tests if this range interests with another
///

/// the other range /// true if they intersect
public bool IntersectsExclusive(DoubleRange range)
{
bool val = _intersects_exclusive(this, range) || _intersects_exclusive(range, this);
return val;
}

public bool IntersectsInclusive(DoubleRange range)
{
bool val = _intersects_inclusive(this, range) || _intersects_inclusive(range, this);
return val;
}

private static bool _touches(DoubleRange range1, DoubleRange range2)
{
var val = (range1.Upper == range2.Lower);
return val;
}

///

/// Tests if this range touches another. For example (1-2) touches (3,5) but (1,2) does not touch (4,5)
///

/// the other range /// true if they touch
public bool Touches(DoubleRange range)
{
var val = _touches(this, range) || _touches(range, this);
return val;
}

///

/// Tests if this range contains a specific double
///

/// the double /// true if the number is contained
public bool Contains(double n)
{
return (this.Lower <= n) && (n <= this.Upper); } ///

/// Join this range with another and return a single range that contains them both. The ranges must either touch or interest.
/// for example (0,2) amd (3,7) will yield (0,7)
///

/// the other range /// the merged range
public DoubleRange JoinWith(DoubleRange range)
{
if (this.IntersectsExclusive(range) || this.Touches(range))
{
double new_Upper = System.Math.Max(this.Upper, range.Upper);
double new_Lower = System.Math.Min(this.Lower, range.Lower);
return DoubleRange.FromEndpoints(new_Lower, new_Upper);
}
else
{
throw new System.ArgumentException(“Ranges cannot be joined because they do not touch or overlap”);
}
}

public IEnumerable Values
{
get
{
double step = 1.0;
return this.GetValues(step);
}
}

public IEnumerable GetValues(double step)
{
if (step <= 0.0) { throw new System.ArgumentOutOfRangeException("step", "must be positive"); } double i = this.Lower; while (i <= this.Upper) { yield return i; i += step; } } } } [/csharp]

Number calculation utils

   
 
#region License

/*
 * Copyright  2002-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#endregion

#region Imports

using System;
using System.ComponentModel;

#endregion

namespace Spring.Util
{
    /// <summary>
    /// Various utility methods relating to numbers.
    /// </summary>
    /// <remarks>
    /// <p>
    /// Mainly for internal use within the framework.
    /// </p>
    /// </remarks>
    /// <author>Aleksandar Seovic</author>
    public sealed class NumberUtils
    {
        /// <summary>
        /// Determines whether the supplied <paramref name="number"/> is an integer.
        /// </summary>
        /// <param name="number">The object to check.</param>
        /// <returns>
        /// <see lang="true"/> if the supplied <paramref name="number"/> is an integer.
        /// </returns>
        public static bool IsInteger(object number)
        {
            return (number is Int32 || number is Int16 || number is Int64 || number is UInt32
                || number is UInt16 || number is UInt64 || number is Byte || number is SByte);
        }

        /// <summary>
        /// Determines whether the supplied <paramref name="number"/> is a decimal number.
        /// </summary>
        /// <param name="number">The object to check.</param>
        /// <returns>
        /// <see lang="true"/> if the supplied <paramref name="number"/> is a decimal number.
        /// </returns>
        public static bool IsDecimal(object number)
        {

            return (number is Single || number is Double || number is Decimal);
        }

        /// <summary>
        /// Determines whether the supplied <paramref name="number"/> is of numeric type.
        /// </summary>
        /// <param name="number">The object to check.</param>
        /// <returns>
        ///   <c>true</c> if the specified object is of numeric type; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsNumber(object number)
        {
            return (IsInteger(number) || IsDecimal(number));
        }

        /// <summary>
        /// Determines whether the supplied <paramref name="number"/> can be converted to an integer.
        /// </summary>
        /// <param name="number">The object to check.</param>
        /// <returns>
        /// <see lang="true"/> if the supplied <paramref name="number"/> can be converted to an integer.
        /// </returns>
        public static bool CanConvertToInteger(object number)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(number);
            return (converter.CanConvertTo(typeof(Int32))
                || converter.CanConvertTo(typeof(Int16))
                || converter.CanConvertTo(typeof(Int64))
                || converter.CanConvertTo(typeof(UInt16))
                || converter.CanConvertTo(typeof(UInt64))
                || converter.CanConvertTo(typeof(Byte))
                || converter.CanConvertTo(typeof(SByte))
                   );
        }

        /// <summary>
        /// Determines whether the supplied <paramref name="number"/> can be converted to an integer.
        /// </summary>
        /// <param name="number">The object to check.</param>
        /// <returns>
        /// <see lang="true"/> if the supplied <paramref name="number"/> can be converted to an integer.
        /// </returns>
        public static bool CanConvertToDecimal(object number)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(number);
            return (converter.CanConvertTo(typeof(Single))
                || converter.CanConvertTo(typeof(Double))
                || converter.CanConvertTo(typeof(Decimal))
                   );
        }

        /// <summary>
        /// Determines whether the supplied <paramref name="number"/> can be converted to a number.
        /// </summary>
        /// <param name="number">The object to check.</param>
        /// <returns>
        ///   <c>true</c> if the specified object is decimal number; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanConvertToNumber(object number)
        {
            return (CanConvertToInteger(number) || CanConvertToDecimal(number));
        }

        /// <summary>
        /// Is the supplied <paramref name="number"/> equal to zero (0)?
        /// </summary>
        /// <param name="number">The number to check.</param>
        /// <returns>
        /// <see lang="true"/> id the supplied <paramref name="number"/> is equal to zero (0).
        /// </returns>
        public static bool IsZero(object number)
        {
            if (number is Int32)
                return ((Int32)number) == 0;
            else if (number is Int16)
                return ((Int16)number) == 0;
            else if (number is Int64)
                return ((Int64)number) == 0;
            else if (number is UInt16)
                return ((Int32)number) == 0;
            else if (number is UInt32)
                return ((Int64)number) == 0;
            else if (number is UInt64)
                return (Convert.ToDecimal(number) == 0);
            else if (number is Byte)
                return ((Int16)number) == 0;
            else if (number is SByte)
                return ((Int16)number) == 0;
            else if (number is Single)
                return ((Single)number) == 0f;
            else if (number is Double)
                return ((Double)number) == 0d;
            else if (number is Decimal)
                return ((Decimal)number) == 0m;
            return false;
        }

        /// <summary>
        /// Negates the supplied <paramref name="number"/>.
        /// </summary>
        /// <param name="number">The number to negate.</param>
        /// <returns>The supplied <paramref name="number"/> negated.</returns>
        /// <exception cref="System.ArgumentException">
        /// If the supplied <paramref name="number"/> is not a supported numeric type.
        /// </exception>
        public static object Negate(object number)
        {
            if (number is Int32)
                return -((Int32)number);
            else if (number is Int16)
                return -((Int16)number);
            else if (number is Int64)
                return -((Int64)number);
            else if (number is UInt16)
                return -((Int32)number);
            else if (number is UInt32)
                return -((Int64)number);
            else if (number is UInt64)
                return -(Convert.ToDecimal(number));
            else if (number is Byte)
                return -((Int16)number);
            else if (number is SByte)
                return -((Int16)number);
            else if (number is Single)
                return -((Single)number);
            else if (number is Double)
                return -((Double)number);
            else if (number is Decimal)
                return -((Decimal)number);
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; is not one of the supported numeric types.", number));
            }
        }

        /// <summary>
        /// Returns the bitwise not (~) of the supplied <paramref name="number"/>.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <returns>The value of ~<paramref name="number"/>.</returns>
        /// <exception cref="System.ArgumentException">
        /// If the supplied <paramref name="number"/> is not a supported numeric type.
        /// </exception>
        public static object BitwiseNot(object number)
        {
            if (number is bool)
                return !((bool)number);
            else if (number is Int32)
                return ~((Int32)number);
            else if (number is Int16)
                return ~((Int16)number);
            else if (number is Int64)
                return ~((Int64)number);
            else if (number is UInt16)
                return ~((UInt16)number);
            else if (number is UInt32)
                return ~((UInt32)number);
            else if (number is UInt64)
                return ~((UInt64)number);
            else if (number is Byte)
                return ~((Byte)number);
            else if (number is SByte)
                return ~((SByte)number);
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; is not one of the supported integer types.", number));
            }
        }

        /// <summary>
        /// Bitwise ANDs (&amp;amp;) the specified integral values.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        /// <exception cref="System.ArgumentException">
        /// If one of the supplied arguments is not a supported integral types.
        /// </exception>
        public static object BitwiseAnd(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is bool)
                return (bool)m &amp; (bool)n;
            else if (n is Int32)
                return (Int32)m &amp; (Int32)n;
            else if (n is Int16)
                return (Int16)m &amp; (Int16)n;
            else if (n is Int64)
                return (Int64)m &amp; (Int64)n;
            else if (n is UInt16)
                return (UInt16)m &amp; (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m &amp; (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m &amp; (UInt64)n;
            else if (n is Byte)
                return (Byte)m &amp; (Byte)n;
            else if (n is SByte)
                return (SByte)m &amp; (SByte)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported integral types.", m, n));
            }
        }

        /// <summary>
        /// Bitwise ORs (|) the specified integral values.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        /// <exception cref="System.ArgumentException">
        /// If one of the supplied arguments is not a supported integral types.
        /// </exception>
        public static object BitwiseOr(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is bool)
                return (bool)m | (bool)n;
            else if (n is Int32)
                return (Int32)m | (Int32)n;
#if NET_2_0
            else if (n is Int16)
                return (Int16)m | (Int16)n;
#endif
            else if (n is Int64)
                return (Int64)m | (Int64)n;
            else if (n is UInt16)
                return (UInt16)m | (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m | (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m | (UInt64)n;
            else if (n is Byte)
                return (Byte)m | (Byte)n;
#if NET_2_0
            else if (n is SByte)
            {
                if (SystemUtils.MonoRuntime)
                {
                    SByte x = (sbyte) n;
                    SByte y = (sbyte) m;
                    int result = (int) x | (int) y;
                    return SByte.Parse(result.ToString());
                }
                return (SByte) ((SByte) m | (SByte) n);
            }
#endif
            throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported integral types.", m, n));
        }

        /// <summary>
        /// Bitwise XORs (^) the specified integral values.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        /// <exception cref="System.ArgumentException">
        /// If one of the supplied arguments is not a supported integral types.
        /// </exception>
        public static object BitwiseXor(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is bool)
                return (bool)m ^ (bool)n;
            else if (n is Int32)
                return (Int32)m ^ (Int32)n;
            else if (n is Int16)
                return (Int16)m ^ (Int16)n;
            else if (n is Int64)
                return (Int64)m ^ (Int64)n;
            else if (n is UInt16)
                return (UInt16)m ^ (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m ^ (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m ^ (UInt64)n;
            else if (n is Byte)
                return (Byte)m ^ (Byte)n;
            else if (n is SByte)
                return (SByte)m ^ (SByte)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported integral types.", m, n));
            }
        }

        /// <summary>
        /// Adds the specified numbers.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        public static object Add(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is Int32)
                return (Int32)m + (Int32)n;
            else if (n is Int16)
                return (Int16)m + (Int16)n;
            else if (n is Int64)
                return (Int64)m + (Int64)n;
            else if (n is UInt16)
                return (UInt16)m + (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m + (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m + (UInt64)n;
            else if (n is Byte)
                return (Byte)m + (Byte)n;
            else if (n is SByte)
                return (SByte)m + (SByte)n;
            else if (n is Single)
                return (Single)m + (Single)n;
            else if (n is Double)
                return (Double)m + (Double)n;
            else if (n is Decimal)
                return (Decimal)m + (Decimal)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported numeric types.", m, n));
            }
        }

        /// <summary>
        /// Subtracts the specified numbers.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        public static object Subtract(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is Int32)
                return (Int32)m - (Int32)n;
            else if (n is Int16)
                return (Int16)m - (Int16)n;
            else if (n is Int64)
                return (Int64)m - (Int64)n;
            else if (n is UInt16)
                return (UInt16)m - (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m - (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m - (UInt64)n;
            else if (n is Byte)
                return (Byte)m - (Byte)n;
            else if (n is SByte)
                return (SByte)m - (SByte)n;
            else if (n is Single)
                return (Single)m - (Single)n;
            else if (n is Double)
                return (Double)m - (Double)n;
            else if (n is Decimal)
                return (Decimal)m - (Decimal)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported numeric types.", m, n));
            }
        }

        /// <summary>
        /// Multiplies the specified numbers.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        public static object Multiply(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is Int32)
                return (Int32)m * (Int32)n;
            else if (n is Int16)
                return (Int16)m * (Int16)n;
            else if (n is Int64)
                return (Int64)m * (Int64)n;
            else if (n is UInt16)
                return (UInt16)m * (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m * (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m * (UInt64)n;
            else if (n is Byte)
                return (Byte)m * (Byte)n;
            else if (n is SByte)
                return (SByte)m * (SByte)n;
            else if (n is Single)
                return (Single)m * (Single)n;
            else if (n is Double)
                return (Double)m * (Double)n;
            else if (n is Decimal)
                return (Decimal)m * (Decimal)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported numeric types.", m, n));
            }
        }

        /// <summary>
        /// Divides the specified numbers.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        public static object Divide(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is Int32)
                return (Int32)m / (Int32)n;
            else if (n is Int16)
                return (Int16)m / (Int16)n;
            else if (n is Int64)
                return (Int64)m / (Int64)n;
            else if (n is UInt16)
                return (UInt16)m / (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m / (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m / (UInt64)n;
            else if (n is Byte)
                return (Byte)m / (Byte)n;
            else if (n is SByte)
                return (SByte)m / (SByte)n;
            else if (n is Single)
                return (Single)m / (Single)n;
            else if (n is Double)
                return (Double)m / (Double)n;
            else if (n is Decimal)
                return (Decimal)m / (Decimal)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported numeric types.", m, n));
            }
        }

        /// <summary>
        /// Calculates remainder for the specified numbers.
        /// </summary>
        /// <param name="m">The first number (dividend).</param>
        /// <param name="n">The second number (divisor).</param>
        public static object Modulus(object m, object n)
        {
            CoerceTypes(ref m, ref n);

            if (n is Int32)
                return (Int32)m % (Int32)n;
            else if (n is Int16)
                return (Int16)m % (Int16)n;
            else if (n is Int64)
                return (Int64)m % (Int64)n;
            else if (n is UInt16)
                return (UInt16)m % (UInt16)n;
            else if (n is UInt32)
                return (UInt32)m % (UInt32)n;
            else if (n is UInt64)
                return (UInt64)m % (UInt64)n;
            else if (n is Byte)
                return (Byte)m % (Byte)n;
            else if (n is SByte)
                return (SByte)m % (SByte)n;
            else if (n is Single)
                return (Single)m % (Single)n;
            else if (n is Double)
                return (Double)m % (Double)n;
            else if (n is Decimal)
                return (Decimal)m % (Decimal)n;
            else
            {
                throw new ArgumentException(string.Format("&#039;{0}&#039; and/or &#039;{1}&#039; are not one of the supported numeric types.", m, n));
            }
        }

        /// <summary>
        /// Raises first number to the power of the second one.
        /// </summary>
        /// <param name="m">The first number.</param>
        /// <param name="n">The second number.</param>
        public static object Power(object m, object n)
        {
            return Math.Pow(Convert.ToDouble(m), Convert.ToDouble(n));
        }

        /// <summary>
        /// Coerces the types so they can be compared.
        /// </summary>
        /// <param name="m">The right.</param>
        /// <param name="n">The left.</param>
        public static void CoerceTypes(ref object m, ref object n)
        {
            TypeCode leftTypeCode = Convert.GetTypeCode(m);
            TypeCode rightTypeCode = Convert.GetTypeCode(n);

            if (leftTypeCode > rightTypeCode)
            {
                n = Convert.ChangeType(n, leftTypeCode);
            }
            else
            {
                m = Convert.ChangeType(m, rightTypeCode);
            }
        }

        #region Constructor (s) / Destructor

        // CLOVER:OFF

        /// <summary>
        /// Creates a new instance of the <see cref="Spring.Util.NumberUtils"/> class.
        /// </summary>
        /// <remarks>
        /// <p>
        /// This is a utility class, and as such exposes no public constructors.
        /// </p>
        /// </remarks>
        private NumberUtils()
        {
        }

        // CLOVER:ON

        #endregion
    }
}

   
     


shows that using an instance of the System.Int32 stucture is the same as using the int keyword


   
 
/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

//
//  TestInt.cs -- shows that using an instance of the System.Int32 stucture
//  is the same as using the int keyword.
//
//                Compile this program with the following command line:
//                    C:>csc TestInt.cs
//
namespace nsTestInt
{
    using System;
    
    public class TestInt
    {
        static public void Main ()
        {
           System.Int32 x;
           OutInt (out x);
           Console.WriteLine ("The integer is " + x);
           x = 42;
           ShowInt (x);
           ChangeInt (ref x);
           Console.WriteLine ("The integer is " + x);
        }
        static void OutInt (out int val)
        {
            val = 42;
        }
        static void ShowInt (int val)
        {
           Console.WriteLine ("The value passed is " + val.ToString());
        }
        static void ChangeInt (ref System.Int32 val)
        {
            val *= 2;
        }
    }
}