Program for method overloading in C #. Method loading always happens in same class. Main intention of method overloading is that we can act to different type of action using same method name. We can change parameter argument types and number of argument.

In my below example,

I am painting various color for different different number of arguments in same method and using method chaining here.

C# program example:

class Painting
    {

        // instance variables.
        String color1;
        String color2;
        String color3;
        String byDefault = "black";

        // Three parameterized method that called by main method.
        public void color(String color1, String color2, String color3) {
 
		// initializing variables.
		this.color1 = color1;
		this.color2 = color2;
		this.color3 = color3;
 
		// calling two parameterized method.
		this.color(color1, color2);

        Console.WriteLine("Color1= " + color1 + " Color2= " + color2 + " Color3= " + color3);
 
	}

        // Two parameterized method is called.
        public void color(String color1, String color2) {
 
		// initializing variables.
		this.color1 = color1;
		this.color2 = color2;
 
		// calling one parameterized constructor.
		this.color(color1);

        Console.WriteLine("Color1= " + color1 + " Color2= " + color2);
 
	}

        // One parameterized method is called.
        public void color(String color1) {
 
		// initializing variables.
		this.color1 = color1;
 
		// calling default parameterized method.
		this.color();

        Console.WriteLine("Color1= " + color1);
 
	}

        // Default parameterized method is called.
        public void color() {
 
		// After print, that will return same way that way it comes.
            Console.WriteLine("Default-color= " + byDefault);
 
	}
    }

    public class TestColorPainting
    {

        public static void Main(String[] args)
        {

            // object is created
            Painting painting = new Painting();

            // calling two parameterized constructor
            painting.color("green", "yellow", "blue");

        }

    }

Output:

Default-color= black
Color1= green
Color1= green Color2= yellow
Color1= green Color2= yellow Color3= blue

Related Posts