none
Easy Question for experienced programmer RRS feed

  • Question

  • Iam newly student of c# and the question is something is wrong with the syntax, what is it?

    public void Calculation(int a, int b)

    {

    return a + b;

    }

    Wednesday, April 3, 2019 7:57 PM

Answers

All replies

  •         public int Calculation(int a, int b)
            {
                return (a + b);
            }


    Wednesday, April 3, 2019 8:09 PM
  • In the previous response, note that the important thing is to use int instead of void. The other change, which introduces parentheses around a+b, is unnnecessary. It won't cause any trouble, but the answer to "something is wrong with the syntax" is that the something wrong is the "void", not the lack of parentheses.
    Saturday, April 6, 2019 1:10 PM
    Moderator
  • Hello,

    Has Castorix31 and Alberto solved this question, if so please consider marking the solution as answered and helpful if this is the case. This will help others with the same or similar question.

    Also if you want to extend this to other types such as decimal, double for instance generics can help.

    using System;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                var resultInt = Add(1, 2);
                var resultDecimal = Add(1.5M, 2.5M);
    
                Console.WriteLine(resultInt);
                Console.WriteLine(resultDecimal);
    
            }
            public T Add<T>(T value1, T value2)
            {
                dynamic a = value1;
                dynamic b = value2;
                return a + b;
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 6, 2019 2:06 PM
    Moderator