Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to make class variable reference another value within the class

Tags:

c#

I have the following simplified class:

public class Foo
{
     public DateTime dateOfBirth {get; set;}
     public Age age {get; set;}
}

and Age is as follows:

Public class Age
{
     public DateTime dateOfBirth {get; set;}    
     //..Calculate age here
}

Now, I want Foo.Age.dateOfBirth to equal Foo.dateOfBirth automatically eg when a user does the following:

var Foo foo = new Foo();
foo.dateOfBirth = //..whatever

Note, this cannot be in the constructor, as the user may not set the Dob in the constructor, and this would also not cover the situation where the Dob changes.

It needs to be a direct reference to the dateOfBirth variable.

Cant his be done?

like image 956
Alex Avatar asked Dec 13 '25 21:12

Alex


1 Answers

You could use the setter:

public class Foo
{
    private DateTime _dateOfBirth;

    public DateTime DateOfBirth
    {
        get { return _dateOfBirth; }
        set {
            _dateOfBirth = value;
            if(Age != null)
               Age.DateOfBirth = value;
        }
    }

    public Age Age { get; set; }
}

If you would make the DateOfBirth property depend on the Age property it was easier, you could use the C#6 expression bodied readonly property:

public class Foo
{
    public DateTime DateOfBirth => Age?.DateOfBirth ?? DateTime.MinValue;
    public Age Age { get; set; }
}
like image 110
Tim Schmelter Avatar answered Dec 16 '25 11:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!