Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
3.33/5 (2 votes)
See more:
Hello,
What is the error of my overloading example?

C#
namespace MethodOverloading
{
    class Program
    {
        public class TestOverloading
        {
            public void Add(string a, string b)
            {
                Console.WriteLine("Adding Two String :" + a + " " + b);
            }
            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Two Integer :" + a1 + a2);
            }

        }
        static void Main(string[] args)
        {
            TestOverloading obj = new TestOverloading();
            obj.Add("Ankit", "Agarwal");
            obj.Add(10,5);
            Console.ReadLine();
        }
    }
}


Output is coming:-
Adding Two String :Ankit Agarwal
Adding Two Integer :105

I want to add two integer value.
why is not coming correct output?

Please help me.

Thanks in Advance.

Ankit Agarwal
Software Engineer
Posted
Comments
BillWoodruff 21-Nov-14 5:13am    
One step of abstraction above just fixing your code: when the Console.WriteLine arguments are evaluated the normal precedence of mathematical operators is ignored.

Change the line to;
Console.WriteLine("Adding Two Integer :" + (a1 + a2));

Otherwise the first addition that takes place is between "Adding Two Integer :" and a1, the result of which is another string. Then when you add a2 to that you're concatenating again.

Hope this helps,
Fredrik
 
Share this answer
 
Comments
[no name] 21-Nov-14 4:31am    
Thanks
Fredrik Bornander 21-Nov-14 4:41am    
Glad I could help.
[no name] 21-Nov-14 4:44am    
Solved my problem
Try this

C#
int c = a1 + a2;
Console.WriteLine("Adding Two Integer :" + c);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900