简体   繁体   中英

C# Not adding a year with .AddYears(1); [duplicate]

This question already has an answer here:

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?

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);

You are displaying the same date which is initially declared,

do this,

bu = nu.AddYears(18);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM