Search code examples
c#ref

Trouble using the ref keyword. Very newbie question!


Here's my class:

public class UserInformation
    {
        public string Username { get; set; }
        public string ComputerName { get; set; }
        public string Workgroup { get; set; }

        public string OperatingSystem { get; set; }
        public string Processor { get; set; }
        public string RAM { get; set; }
        public string IPAddress { get; set; }

        public UserInformation GetUserInformation()
        {
            var CompleteInformation = new UserInformation();

            GetPersonalDetails(ref CompleteInformation);
            GetMachineDetails(ref CompleteInformation);

            return CompleteInformation;
        }

        private void GetPersonalDetails(ref UserInformation CompleteInformation)
        {

        }

        private void GetMachineDetails(ref UserInformation CompleteInformation)
        {

        }
    }

I'm under the impression that the ref keyword tells the computer to use the same variable and not create a new one.

Am I using it correctly? Do I have to use ref on both the calling code line and the actual method implementation?


Solution

  • When you pass a reference type (in your case, your UserInformation class is a reference type) as a parameter, by default you are passing the pointer to the class by value, meaning the GetPersonalDetails would get its own copy of a pointer which points to the same instance of the UserInformation class.

    Using the ref keyword in your example will pass the same pointer to the UserInformationinstance to the method.

    So in your case, if your intent is to simple modify the properties of UserInformation, the ref keyword in not needed, since you will be modifying the actual instance from GetPersonalDetails and GetMachineDetails. However, if your intent is to instantiate a new UserInformation object from inside those methods or set the instance to null, you would need to use the ref keyword.

    Jon Skeet does a great job of explaining parameter passing in this article.