#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!!
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: