#674 – Can Overload If Parameters Differ Only by ref Modifier

You can overload methods, i.e. create two methods with the same name, if the methods have different parameter lists, where the lists differ in the number or type of the parameters.  For example:

        public void Fetch(Bone b)
        {
            Console.WriteLine(string.Format("Fetching bone {0}", b.Description));
        }

        public void Fetch(Dog d)
        {
            Console.WriteLine(string.Format("I'll go get {0}", d.Name));
        }

You can also overload methods if they differ only in their use of the ref modifier.  One method can accept a parameter passed by value and you can have another version of the method that allows passing the parameter by reference.

        public void Bark(string sound)
        {
            Console.WriteLine(sound);
        }

        public void Bark(ref string sound)
        {
            Console.WriteLine(sound);

            // Update caller's copy of sound variable
            sound = sound + "!";
        }
            Dog d = new Dog("Rex", 3);
            string sound = "woof";
            d.Bark(sound);
            d.Bark(ref sound);   // woof!
            d.Bark(ref sound);   // woof!!
Advertisements