Math

using System;
class Program
{
static void Main()
{
*// Version 1: get the bigger value with Math.Max.*
int a = 4;
Console.WriteLine(Math.Max(0, a));
*// Version 2: get the bigger value with if.*
int result = a;
if (0 > a)
{
result = 0;
}
else
{
result = a;
}
Console.WriteLine(result);
}
}4
4

if

return

using System;
class Program
{
static int[] _array = new int[]
{
1,
2,
5,
6,
7
};
static void Main()
{
*// Get 1 place from end.*
int i = GetLastIndex(1);
Console.WriteLine(i);
*// Get 3 places from end.*
i = GetLastIndex(3);
Console.WriteLine(i);
*// Get 10 places from end. Will not throw exception.*
i = GetLastIndex(10);
Console.WriteLine(i);
}
static int GetLastIndex(int length)
{
int start = _array.Length - length - 1;
start = Math.Max(0, start);
return _array[start];
}
}6
2
1

int

double

decimal

using System;
class Program
{
static void Main()
{
*//*
*// Use Math.Min on positive integers.*
*//*
int value1 = 4;
int value2 = 8;
int minimum1 = Math.Min(value1, value2);
Console.WriteLine(minimum1);
*//*
*// Use Math.Min on negative and positive integers.*
*//*
int value3 = -1000;
int value4 = 100;
int minimum2 = Math.Min(value3, value4);
Console.WriteLine(minimum2);
}
}4
-1000

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int Min(int val1, int val2)
{
if (val1 > val2)
{
return val2;
}
return val1;
}

Max, Min

Ternary

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Feb 19, 2023 (edit).