.NET provides a rich set of numeric types covering integers, floating-point, and arbitrary-precision arithmetic.
int a = 42; // 32-bit signed integer
long b = 42L; // 64-bit signed integer
short c = 42; // 16-bit signed integer
byte d = 42; // 8-bit unsigned integer
uint e = 42U; // 32-bit unsigned integer
ulong f = 42UL; // 64-bit unsigned integer
float f = 3.14f; // 32-bit, ~7 digits precision
double d = 3.14; // 64-bit, ~15 digits precision
decimal m = 3.14m; // 128-bit, 28-29 digits precision, exact decimal
Use decimal for financial and monetary calculations where exact representation is crucial. Use double for scientific computing. Use float for graphics and GPU computations.
For arbitrarily large integers, use System.Numerics.BigInteger:
using System.Numerics;
BigInteger huge = BigInteger.Parse("123456789012345678901234567890");
BigInteger result = huge * huge;
Console.WriteLine(result);
The Math class provides static methods for trigonometric, logarithmic, and algebraic operations on double. MathF is the float equivalent:
double sqrt = Math.Sqrt(144); // 12.0
double power = Math.Pow(2, 10); // 1024.0
double pi = Math.PI; // 3.14159...
float sin = MathF.Sin(MathF.PI / 2); // 1.0f
Strings are immutable in .NET. Common operations include concatenation, interpolation, and parsing:
string name = "Alice";
string greeting = $"Hello, {name}!";
string upper = greeting.ToUpper();
int length = greeting.Length;
DateTime now = DateTime.Now;
DateTime utc = DateTime.UtcNow;
DateTime birthday = new DateTime(1990, 6, 15);
TimeSpan age = now - birthday;
int daysOld = (int)age.TotalDays;
.NET provides several collection types for different scenarios:
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.Add("Diana");
Dictionary<string, int> scores = new()
{
["Alice"] = 95,
["Bob"] = 87
};
HashSet<int> unique = new() { 1, 2, 3, 3 }; // contains {1, 2, 3}
Queue<string> queue = new(); // FIFO
Stack<string> stack = new(); // LIFO
Language Integrated Query (LINQ) allows you to query collections with a SQL-like syntax or method chains:
int[] numbers = { 5, 2, 8, 3, 1, 9, 4 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
var sorted = numbers.OrderBy(n => n);
var grouped = numbers.GroupBy(n => n % 2 == 0 ? "even" : "odd");
var sum = numbers.Aggregate((a, b) => a + b);
.ToList() or .ToArray() to materialize results immediately.