0

I was playing with function overloading in C#. The below code made me to realize that double datatype can accommodate float value:

class program
{
    static void Main(string[] args)
    {
        test(2f);
        Console.Read();
    }

    static void test(double a)
    {
        Console.WriteLine("double called" + a);
    }
}

Same as above code, i also found that float can accommodate int value. Double can accommodate int and float both values.

First i thought it is due to the range of the datatypes.

But decimal changed my thought as below code is not compiling:

class Program
{
    static void Main(string[] args)
    {
        test(2d);   //Invalid argument error
        Console.Read();
    }

    static void test(decimal a)
    {
        Console.WriteLine("decimal called" + a);
    }
}

Why decimal datatype can not accommodate float and double values, whereas double datatype can accommodate float value and float datatype can accommodate int value?

stackuser83
  • 2,012
  • 1
  • 24
  • 41
Sometimes Code
  • 591
  • 3
  • 14
  • 33
  • [`Double`](https://msdn.microsoft.com/en-us/library/678hzkk9.aspx) and [`Float`](https://msdn.microsoft.com/en-us/library/b1e65aza.aspx) both have a larger range than [`Decimal`](https://msdn.microsoft.com/en-us/library/364x0z75.aspx). And the reason you cannot implicitly convert the other way is because of precision. – juharr Jun 08 '16 at 18:42
  • @juharr: Then double should accommodate decimal value but it can't.. – Sometimes Code Jun 08 '16 at 18:47
  • As I mentioned the reason double doesn't accommodate decimal is because, while double covers decimal's range, it has less precision. Thus conversions between the two could result in data loss either way. – juharr Jun 08 '16 at 19:06

0 Answers0