In C # object initializer syntax Why can't we assign it one property to another?

Hi I have used C # Object Initializer like

public class Invoice
    {
        public decimal GrossSum { get; set; }
        public decimal GrossSumComp { get; set; }
    }
    public class ABC()
    {
        public Invoice Invoice {get;set;}

        public ABC(decimal grossSum)
        {
            Invoice=new Invoice()
            {
                GrossSum=grossSum,
                GrossSumComp=**GrossSum**
            };
        }
    }

      

And I saw that we cannot assign the value of One Property to another in it. As above, I tried to assign GrossSum to GrossSumComp and there I got Compilation error. Just curious to know why it doesn't allow it. Any help would be much appreciated.

+3


source to share


2 answers


Because that is how it was indicated. GrossSum

the second line contains a reference to a variable with a name GrossSum

, and not to a property of the object being initialized.

To paraphrase Eric Lippert. For a function to be implemented, it must be

  • The proposed
  • Analyzed
  • Design
  • Implemented
  • Tested


They all incur costs, so they must add value to match the cost and preferably exceed the cost.

If there is a simple operation of the function, the likelihood that the cost will be (much) higher than the potential value.

In your case, you can simply assign GrossSum

instead GrossSum

. It's a simple work around

+2


source


The error message in this case is your answer:

The name 'GrossSum' does not exist in the current context

      



How does the compiler know that it GrossSum

does not have a given context? There is no way to specify this

or anything similar to indicate that the property GrossSum

you are referring to is the one that is defined for the object you are initializing.

+1


source







All Articles