Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find minimum between 2 numbers using C#?
Finding the minimum between two numbers in C# can be accomplished using several approaches. The most common methods include using conditional statements like if-else or utilizing built-in methods like Math.Min().
Using if-else Statement
The traditional approach uses an if-else statement to compare two numbers and determine the smaller value −
using System;
class Program {
static void Main(string[] args) {
int num1 = 50;
int num2 = 90;
int minNum;
Console.WriteLine("Number 1: " + num1);
Console.WriteLine("Number 2: " + num2);
if (num1
The output of the above code is −
Number 1: 50
Number 2: 90
Minimum number is: 50
Using Math.Min() Method
C# provides the built-in Math.Min() method which directly returns the smaller of two values. This is the most efficient and concise approach −
using System;
class Program {
static void Main(string[] args) {
int num1 = 35;
int num2 = 55;
Console.WriteLine("Number 1: " + num1);
Console.WriteLine("Number 2: " + num2);
int minNum = Math.Min(num1, num2);
Console.WriteLine("Minimum number is: " + minNum);
}
}
The output of the above code is −
Number 1: 35
Number 2: 55
Minimum number is: 35
Using Ternary Operator
The ternary operator provides a compact way to find the minimum in a single line −
using System;
class Program {
static void Main(string[] args) {
double num1 = 25.5;
double num2 = 18.3;
Console.WriteLine("Number 1: " + num1);
Console.WriteLine("Number 2: " + num2);
double minNum = (num1
The output of the above code is −
Number 1: 25.5
Number 2: 18.3
Minimum number is: 18.3
Comparison of Approaches
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| if-else Statement | High | Good | Learning purposes, complex logic |
| Math.Min() | Very High | Best | Production code, recommended approach |
| Ternary Operator | Medium | Good | Inline assignments, compact code |
Conclusion
The Math.Min() method is the recommended approach for finding the minimum between two numbers in C# due to its simplicity and built-in optimization. The if-else statement remains useful for educational purposes and when additional logic is required alongside the comparison.
