Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C# returning a constructor

  1. Jun 11, 2015 #1
    I find that people can do this in C#
    Code (Text):

    public decimal func()
        return new Decimal(....)
    and use it like this
    Code (Text):
    My question is how can the constructor returned in func() be output like that ? Thank you.
  2. jcsd
  3. Jun 11, 2015 #2


    Staff: Mentor

    The constructor is not being returned. In the call to Writeline, the expression func() is evaluated, which causes the Decimal constructor to be called. The Decimal constructor creates an instance of a Decimal struct and returns it to the caller, func().

    In your func() definition, shouldn't the header be public Decimal func()?
  4. Jun 11, 2015 #3


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    Does it make more sense to you if it's written this way? It's the same thing as what you wrote.
    Code (C):
    public decimal func()
        decimal dec = new Decimal(...);
        return dec;
  5. Jun 11, 2015 #4
    Yes, but I'd still like to know what is "dec" that is being returned. I don't think it's a raw number being fed into WriteLine.
    Well, the constructor is like this, for example,
    Code (Text):

    return new Decimal (18,2,false,bits);
  6. Jun 11, 2015 #5
    Thank you Mark44, it should be Decimal in that line.
  7. Jun 11, 2015 #6
    Actually I think it is a string, not a number that is being passed into WriteLine. But I don't know when it has been converted to a string ?
    This seems more understandable
    Code (Text):

    dec=new Decimal(...);
    return dec.Value;
  8. Jun 11, 2015 #7

    Filip Larsen

    User Avatar
    Gold Member

    Your func() returns an instance of the value type Decimal [1,2] which is boxed [3] in the call to Console.Writeline [4] (since its a value type [5]) and then finally converted to a string within the Console.Writeline method by one of the Decimal.ToString methods. By the way, note that decimal is shorthand for System.Decimal.

    [1] https://msdn.microsoft.com/en-us//library/364x0z75.aspx
    [2] https://msdn.microsoft.com/en-us/library/system.decimal.aspx
    [3] https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
    [4] https://msdn.microsoft.com/en-us/library/586y06yf.aspx
    [5] https://msdn.microsoft.com/en-us/library/s1ax56ch.aspx
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook