Extension method for integer : Extension Method : LINQ C# Source Code


Custom Search

C# Source Code » LINQ » Extension Method »

 

Extension method for integer








    
 


using System;

static class MainClass {
    public static int ConvertToBase(this int i, int baseToConvertTo) {
        if (baseToConvertTo < 2 || baseToConvertTo > 10)
            throw new ArgumentException("Value cannot be converted to base " + baseToConvertTo.ToString());
        int result = 0;
        int iterations = 0;
        do {
            int nextDigit = i % baseToConvertTo;
            result += nextDigit * (int)Math.Pow(10, iterations);
            iterations++;
            i /= baseToConvertTo;
        }
        while (i != 0);
        return result;
    }
    static void Main() {
        try {
            int x = 591;
            for (int i = 2; i <= 10; i++) {
                Console.WriteLine("{0} in base {1} is {2}", x, i, x.ConvertToBase(i));
            }
        } catch (Exception ex) {
            Console.WriteLine("Exception: {0}", ex.Message);
        }
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo LINQ
» Extension Method