C# Tutorial · C# Basics · Lesson 6 of 22

C# Operators and Math

Arithmetic, comparison, logical, null operators and the Math class.

Operators

Example 1
int a = 17, b = 5;
Console.WriteLine($"{a + b} {a - b} {a * b} {a / b} {a % b}");
Console.WriteLine(a > b && b > 0);
string s1 = "hi", s2 = string.Concat("h", "i");
Console.WriteLine(s1 == s2);
string? nickname = null;
Console.WriteLine(nickname ?? "Anonymous");
Console.WriteLine(nickname?.Length is null);   // ?. gave null instead of throwing
nickname ??= "Guest";
Console.WriteLine(nickname);
Console.WriteLine(a % 2 == 0 ? "even" : "odd");

Output

22 12 85 3 2
True
True
Anonymous
True
Guest
odd

Run this on your computer — see “Get Started” for setup.

  • == on strings compares contents in C# (unlike Java).
  • ?? gives a default for null; ?. safely accesses members of a possibly-null object; ??= assigns when null.
  • The ternary cond ? a : b picks a value.

Math

Example 2
Console.WriteLine(Math.Max(4, 9) + " " + Math.Min(4, 9));
Console.WriteLine(Math.Sqrt(144) + " " + Math.Pow(2, 10) + " " + Math.Abs(-7));
Console.WriteLine(Math.Round(2.5) + " " + Math.Round(3.5) + " " + Math.Round(2.5, MidpointRounding.AwayFromZero));
Console.WriteLine(Math.Floor(2.7) + " " + Math.Ceiling(2.1));
Console.WriteLine(Math.Round(Math.PI, 4));

Output

9 4
12 1024 7
2 4 3
2 3
3.1416

Run this on your computer — see “Get Started” for setup.

Test yourself

What does null ?? "x" return?

  1. null
  2. "x"
  3. An exception
  4. ""
Show answer

Answer: "x"