0

The output of below code is &&&2022-05-22 19:49:31&&&2022-05-22 19:49:31. It consists of two parts. I don't quite understand why because previouly I thought it should only one part. I thought in the second loop of Main method, it creates a new instance of Utilities class, so every variable of the new Utilities instance should be new, so it will be a new user with empty Result.

But in the second loop, it actually uses the same User instance which is created in the first loop. Could you help explain why?

    public class User
    {
        public string Result { get; set; } = string.Empty;
    }

    internal class Utilities
    {
        internal static User user = new User();
        internal User ProcessUser()
        {
            user.Result = user.Result + "&&&" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            return user;
        }
    }

    static void Main(string[] args)
    {
            string finalResult="";
            for (int i = 0; i < 2; i++)
            {
                User u = new User();
                Utilities utilities = new Utilities();
                u = utilities.ProcessUser();
                finalResult = u.Result;
            }
            Console.WriteLine(finalResult);
            Console.Read();
    }
Robin Sun
  • 1,045
  • 3
  • 15
  • 31

0 Answers0