Home > Software design >  How to set calculate variable to property in class
How to set calculate variable to property in class

Time:01-25

I have a following class and i want to set YearCreated = 2023-age how i can do it ?

public class Car
{
    public string Id { get; set; }
    public Producent Producent { get; set; }
    public int Age { get; set; }
    public int YearCreated { get; set; } 
    public Engine Engine { get; set; }

}

CodePudding user response:

Here you can find details Using Properties

It will be something like

 public class Car
    {
        public int Age { get; set; }
        public int YearCreated => DateTime.Now.Year - Age;
    }

CodePudding user response:

You could turn YearCreated into an expression-bodied property. See below for example.

Note that this makes the property read-only. If you need to be able to override the property, you will need to add a backing field and give the property a body.

public class Car
{
    public string Id { get; set; }
    public Producent Producent { get; set; }
    public int Age { get; set; }
    public int YearCreated => 2023 - Age;
    public Engine Engine { get; set; }
}
  •  Tags:  
  • c#
  • Related