0

This smells like a scoping issue with my variable however moving it does not seem to help. Here is a very simple example. I create the currentDay variable. I set it's value. I then call another method which should change the value of currentDay, but it never changes. Just Monday morning blindness?

void Main()
{
    SetScheduleTicketsDate();
}

public static void SetScheduleTicketsDate()
{
    DateTime currentDay = DateTime.Now;
    SchedulePatchGroup(currentDay);
    Console.WriteLine(currentDay);
}

private static void SchedulePatchGroup(DateTime currentDay)
{
    currentDay = currentDay.AddDays(10);
}
2
  • What if you change it to return currentDay.AddDays(10);? Commented Mar 26, 2018 at 15:14
  • 2
    Also, I believe that DateTime is a value-type, not a reference type. Commented Mar 26, 2018 at 15:14

1 Answer 1

5

Assigning a parameter will not propagate to the caller unless you use ref or out.

Usually that's a code smell; your method should probably just return the updated object anyways.

public static void SetScheduleTicketsDate()
{
    DateTime currentDay = DateTime.Now;
    currentDay = SchedulePatchGroup(currentDay);
    Console.WriteLine(currentDay);
}

private static DateTime SchedulePatchGroup(DateTime currentDay)
{
    return currentDay.AddDays(10);
}

Just using currentDay.AddDays(10) won't do anything either since DateTime is a value type; AddDays does not mutate the current instance and instead returns a new one.

Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps would be worth noting in your answer that DateTime is not a reference type (which is maybe where the confusion is).
Yeah, I would have expected it to mutate the current value like other variables. This makes sense. My SchedulePatchGroup does its thing, coming up with a new currentDay and then returns it rather than directly setting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.