3

I'm trying testing the C# .AddYears(); function but for some reason I can't get it to work.

nu = DateTime.Now;
MessageBox.Show(nu.ToString());
nu.AddYears(18);
MessageBox.Show(nu.ToString());

Why are both MessageBoxes exactly the same?

It doesn't seem to add 18 years to my nu variable for some reason.

Does anyone know what I'm doing wrong in this code?

user4598368
  • 65
  • 1
  • 2
  • 7

2 Answers2

13

DateTime values are immutable. AddYears does not modify the current instance, but instead returns a new one.

That means you should do:

nu = nu.AddYears(18);
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
2

You are displaying the same date which is initially declared,

do this,

bu = nu.AddYears(18);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396