C# Half Type — Complete Guide
In this tutorial, you'll learn about C# Half Type. We cover key concepts, practical examples, and best practices.
You need to store thousands of floating-point values where 32-bit float wastes memory or 16-bit precision is sufficient (GPU data, ML models, audio samples). You could use float and waste space, or write a custom 16-bit float. .NET provides Half — an IEEE 754 16-bit floating-point type.
Wrong
// Using float for half-precision data
float[] samples = new float[1_000_000];
// 4 MB of memory for data that only needs 2 MB
// No validation that values fit in half precision
Output: Works, but uses twice the necessary memory.
Right
Half[] samples = new Half[1_000_000];
samples[0] = (Half)3.14f;
samples[1] = Half.Parse("2.718");
Console.WriteLine(samples[0]); // 3.14
Output: 3.14 — stored in 2 bytes instead of 4.
Half follows IEEE 754 with 1 sign bit, 5 exponent bits, and 10 mantissa bits. Range is approximately ±65,504 with ~3.3 decimal digits of precision.
// Conversion
float f = (float)samples[0];
Half h = (Half)3.14159f; // Rounds to 3.14
// Math
Half a = (Half)1.5;
Half b = (Half)2.5;
Half c = (Half)((float)a + (float)b); // No direct arithmetic
Prevention
- Use
Halffor large arrays of floating-point data when 16-bit precision is sufficient. - Use
Halfin machine learning model weights, audio samples, and GPU interop. - Use
floatordoublewhen arithmetic precision matters —Halfhas limited precision. - Convert to
floatbefore arithmetic operations —Halfdoes not support direct arithmetic operators. - Use
HalfwithSpan<Half>andMemory<Half>for efficient buffer management. - Use
Half.MaxValue/Half.MinValue/Half.Epsilonconstants.
Common Mistakes with half type
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Half is used in Durga Antivirus Pro for audio signature matching. For more .NET numeric types, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro