This tutorial uses the same code as Add two numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.
The source code
using System; // for the console object class addtwonumbers { public static int addIntegers(int a, int b) { return (a + b); } public static void Main() { try { // output to the console Console.Write("Please enter value 1 : "); // readin the console input, and then convert to a integer value int val1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Please enter value 2 : "); int val2 = Convert.ToInt32(Console.ReadLine()); // write out the answer Console.WriteLine("Answer = " + addIntegers(val1,val2)); } catch (Exception e) { // any errors. Like converting a string to a integer value Console.WriteLine("Error : " + e.ToString()); } } } |
save as addtwonumbers_function.cs, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.
hello creators,
this is mini..i have searched for this concepts in many sites..after my long search i got this useful site…as because am a beginner in c#..something like this explanation is needed to guide us..thanks a lot for your informative site..
Thanks for the great tutorial , I’ve been searching for this concept a lot of time but no help..
But now I understand it thanks a lot!
could you give the code for beginers
The beginers code as such, can be found here.
In essence it is
// output to the console
Console.Write(“Please enter value 1 : “);
// readin the console input, and then convert to a integer value
int val1 = Convert.ToInt32(Console.ReadLine());
Console.Write(“Please enter value 2 : “);
int val2 = Convert.ToInt32(Console.ReadLine());
// write out the answer
Console.WriteLine(“Answer = ” + (val1 + val2));
This site was very usefull to me as i am new to .net.. Thanks a ton to codingfriends.com
Thanks a lot… U done a great job…..
this is very simple calculator. easy to understand
thanks alot !!
its really working very well….thnx