Addition of Two Numbers in C# using Class and Methods
ADVERTISEMENTS
Addition of two numbers in C# using class.
In this article, you will learn how to make an addition of two numbers in C# using class.
Example
Enter two integer values::
10
20
Result:: 10 + 20 = 30
You should have knowledge of the following topics in C# programming to understand this program:
- C# Oops Concepts
- C# System Library
- C# Methods
Source Code
// Addition of Two Numbers in C# using Class and Methods
using System;
public class W3CW {
// To make the sum of two numbers
public int sum(int x, int y) {
return x + y;
}
// @It's the driver function
static public void Main (string[] args) {
Console.WriteLine("Enter two integer values::");
int p = Convert.ToInt32(Console.ReadLine());
int q = Convert.ToInt32(Console.ReadLine());
W3CW Obj = new W3CW();
int sum = Obj.sum(p, q);
// It will print the final output
Console.Write("\nResult:: " + p + " + " + q + " = " + sum);
}
}
Output
Enter two integer values::
10
20
Result:: 10 + 20 = 30
Explanation
In the above program, we have taken two inputs 10
and 20
from the user via the system console. Then we applied the arithmetic operation on these values after that It will return the value 30
the output of the program.
Addition of Two Numbers in C# using Function
// Addition of Two Numbers in C# using Function
using System;
public class W3CW {
// To make the sum of two numbers
public static int Sum(int x, int y) {
return x + y;
}
// @It's the driver function
static public void Main (string[] args) {
Console.WriteLine("Enter two integer values::");
int p = Convert.ToInt32(Console.ReadLine());
int q = Convert.ToInt32(Console.ReadLine());
// It will print the final output
Console.Write("\nResult:: " + p + " + " + q + " = " + Sum(p, q));
}
}
Addition of Two Numbers in C# using Generics
// Addition of Two Numbers in C# using Generics
using System;
public class W3CW {
// To make the sum of two numbers <Generic method>
public int Sum<T>(T x, T y) {
dynamic a=x;
dynamic b=y;
return a+b;
}
// @It's the driver function
static public void Main (string[] args) {
Console.WriteLine("Enter two integer values::");
int p = Convert.ToInt32(Console.ReadLine());
int q = Convert.ToInt32(Console.ReadLine());
W3CW Obj = new W3CW();
int sum = Obj.Sum<int>(p, q);
// It will print the final output
Console.Write("\nResult:: " + p + " + " + q + " = " + sum);
}
}