11 — BCL value types, Type objects and library helpers
This page covers the library types csharpc implements natively instead of compiling the BCL:
System.Decimal, TimeSpan, DateTime, Stopwatch, BigInteger, System.Type
(“reflection-lite”), plus BitOperations, System.Array helpers, Convert, culture-sensitive
string comparison and a number of smaller members. Everything here is verified with differential
samples against real .NET 11 (tests/samples/80_decimal.cs … 86_biginteger.cs).
Code map:
| Piece | Where |
|---|---|
| Member table (methods, getters, ctors, operators, static fields) | src/Csharpc/CodeGen/BclValueTypes.cs |
| Per-function helpers (decimal ops, Type objects, loops, delegate calls) | src/Csharpc/CodeGen/FunctionCodeGen.Bcl.cs |
Array / enum / type-only method tables, IR comparers for Array.Sort |
src/Csharpc/CodeGen/ModuleCodeGen.Bcl.cs |
| Decimal arithmetic, conversions, parsing | src/Csharpc/corelib/DecimalOps.cs (C#, ADR 0008) |
| TimeSpan, DateTime arithmetic, calendar, time zones and formatting | src/Csharpc/corelib/DateTimeOps.cs (DateTimeMembers shadows the rest of DateTime); clocks and Stopwatch in src/runtime/datetime.c |
System.Type objects |
src/runtime/type.c |
| BigInteger | the framework’s IL (System.Runtime.Numerics, docs/il-first/System.Runtime.Numerics.md) |
| Array helpers, introsort, Convert, Environment, collation | src/runtime/bclmisc.c |
| Number formatting and parsing (decimal included) | src/Csharpc/corelib/Number.Formatting.cs, Number.Parsing.cs |
| Boxed decimal / BigInteger / TimeSpan / DateTime method tables | src/runtime/{decimal,bigint,datetime}.c (their slots call corelib exports) |
How library members are dispatched
Roslyn binds user code against the real reference assemblies, so every call site names an exact
BCL member. Lowering looks members up by the Intrinsics.Key format
("System.TimeSpan.FromMinutes(double)", "decimal.Round(decimal, int)", accessors as
get_X, constructors as .ctor, operators as op_X):
Intrinsics(the original table) — consulted first.BclValueTypes.TryGetRaw— handlers that need the unevaluated invocation: overloads takingparams ReadOnlySpan<T>that C# 13 prefers forstring.Join(",", a, b, c),string.Format/Console.WriteLinewith 4+ arguments, and collection-expression arguments.BclValueTypes.TryGet— handlers receiving the evaluated receiver and arguments (by-ref arguments as addresses).
The same table serves property getters, library constructors (class and struct), library
operator methods (TimeSpan + TimeSpan, Type == Type, BigInteger * BigInteger), compound
assignment and ++/-- through library operators, interface calls devirtualized to library
implementations, and static library fields (string.Empty, TimeSpan.Zero,
Stopwatch.Frequency, …).
System.Decimal
- Representation: the CLR’s own layout,
{ i32 flags, i32 hi32, i64 lo64 }(scale in bits 16–23 offlags, sign in bit 31). Constants are emitted fromdecimal.GetBits. - Arithmetic (
corelib/DecimalOps.cs) computes the exact result with a small bignum, then fits it into 96 bits / scale ≤ 28 by dividing by a power of ten with round-half-to-even, which is the CLR’s contract. Scale rules follow .NET:+/-keep the larger scale,*adds scales,/produces the smallest scale that represents the quotient exactly (up to 28 digits),%keeps the larger scale and the dividend’s sign, and returns the dividend unchanged when its magnitude is smaller than the divisor’s (asDecCalc.VarDecModdoes). Overflow throwsOverflowException(“Value was either too large or too small for a Decimal.”); division by zero throwsDivideByZeroException. - Conversions:
int/long→ decimal are exact;double→ decimal is exact in .NET 11 ((decimal)0.1 == 0.1000000000000000055511151231) and is implemented from the double’s exact decimal expansion; decimal → integer truncates and always throws on overflow (C# semantics); decimal → double is correctly rounded (what .NET 11 does). - Formatting:
ToString()keeps trailing zeros from the scale (1.50m→"1.50"); negative zero prints without a sign. Format strings (F,N,E,P,C,G, custom) round the exact digits half away from zero (unlikedouble, which rounds ties to even). Math.Round/Floor/Ceiling/Truncate/Abs/Max/Min/Sign,decimal.Parse/TryParse(NumberStyles.Number), boxing (csrt_Boxed_Decimal_MT),GetHashCode(normalized, so1.0mand1.00mhash alike).
TimeSpan, DateTime, Stopwatch
-
TimeSpanis lowered to its tick count (i64, 100 ns units).DateTimeis .NET’s own_dateDataword (i64): ticks in bits 0–61 and the Kind in bits 62–63 (Unspecified 0, Utc 1, Local 2, and 3 for a Local time in the daylight-saving occurrence of an ambiguous hour, .NET’sKindLocalAmbiguousDst).Ticksmasks the Kind off; arithmetic (Add*,+/-TimeSpan,Date) keeps every kind bit; equality, ordering and hashing look at the ticks only (==,Equals,CompareTo,EqualityComparer/Comparer,Dictionarykeys, boxedEqualsandGetHashCode, records, tuples, and the defaultValueType.Equals/GetHashCodeof structs withDateTimefields, which compare field by field with each field’s ownEquals).UtcNowandUnixEpochare Utc;NowandTodayare Local;MinValue,MaxValueanddefaultare Unspecified. -
Time zones come from libc (
localtime_rover tzdata andTZ, which .NET reads too), resolved likeTimeZoneInfo.Local(checked against .NET in New York, London, Amsterdam, Dublin, Moscow, Sao Paulo, St. John’s, Monrovia, Kolkata, Sydney, Lord Howe, Chatham, Apia, Kiritimati, Yakutat, Sitka, Manila, Guam and UTC):- a wall-clock (Unspecified or Local) time in an ambiguous hour takes standard time unless it is a
Local value flagged as the daylight-saving occurrence; a skipped time takes the zone’s base
offset and is never daylight-saving time;
IsDaylightSavingTime()is false in both cases; ToUniversalTime()treats Unspecified as local and, like .NET, adds the offset of a skipped time (02:30 on a New York spring-forward day becomes 21:30Z the day before);ToLocalTime()treats Unspecified as UTC and sets the ambiguous-hour flag; both conversions clamp toMinValue/MaxValue;- local mean times keep only the hours and minutes of their difference to the base offset (New York’s -4:56:02 is -4:57; Apia’s -11:26:04 against +13 wraps to +12:34), offsets are clamped to ±14 h (Yakutat’s +14:41 is +14:00), and a daylight-saving period still running at the end of year 9999 ends at local midnight.
Samples
188–190pin a zone withEnvironment.SetEnvironmentVariable("TZ", ...)before anything reads the local zone (both .NET and libc load it lazily), so their recorded output does not depend on the machine’s zone. - a wall-clock (Unspecified or Local) time in an ambiguous hour takes standard time unless it is a
Local value flagged as the daylight-saving occurrence; a skipped time takes the zone’s base
offset and is never daylight-saving time;
-
SpecifyKind,ToBinary/FromBinary,ToFileTime[Utc]/FromFileTime[Utc],Equals(object),CompareTo(object)and the conversions above are C# shadows (DateTimeMembers); invalid kinds throwArgumentExceptionlike .NET. ADateTimeP/Invoke parameter or return is diagnosed as unsupported (.NET marshals it as an OLE Automation date). -
Calendar math is the CLR’s own algorithm (proleptic Gregorian, years 1–9999):
AddMonthsclamps the day,AddDays(double)adds integral and fractional parts separately (.NET 7+ behaviour), range errors throwArgumentOutOfRangeExceptionwith .NET’s messages. -
TimeSpan.FromX(double)truncates exact ticks (.NET 7+); the .NET 9 integer overloads (FromSeconds(long),FromHours(int, long minutes = 0, ...)) are recognised by parameter names.TimeSpan * doubleand/ doubleround ticks to even like .NET. -
Formatting follows the invariant culture:
TimeSpanc/g/Gand custom formats (hh\:mm\:ss);DateTimestandard formats (d D f F g G M Y t T s u U o R) and custom formats (yyyy-MM-dd HH:mm:ss.fff,dddd,MMMM,tt,Ftrimming that drops a dangling.).KwritesZfor Utc, the local offset for Local and nothing for Unspecified;z/zz/zzzwrite+00:00for Utc and the local offset otherwise (a bare time of day below one day gets today’s offset, even for Utc, as in .NET);o/Oend withK;Uconverts to universal time first, whileranduformat the value as it is. -
Stopwatchis a runtime object onCLOCK_MONOTONIC;Stopwatch.Frequencyis 1 000 000 000 (so its ticks are nanoseconds, as on Linux .NET).ToString()returnsElapsed.ToString().
System.Type (reflection-lite)
- One canonical Type object per method table, cached in a
.bsstable that the conservative GC scans. Sotypeof(X) == obj.GetType()is a pointer comparison. obj.GetType()is static for value-type receivers and reads the object’s method table otherwise.Name,FullName,NamespaceandToString()derive from the MT’s CLR name ("Program+Nested","MyNs.Point","System.Int32[]").- Every type gets an identifying method table: classes/structs reuse theirs, primitives use
their boxed MTs, enums get a boxed-enum MT (also used for boxing enums, whose
ToStringformats by name), library types get a name-only MT, and arrays get an element-typed array MT stamped right after allocation, sonew int[3].GetType().Name == "Int32[]"andarray.ToString() == "System.Int32[]". Arrays of reference-free elements carryCSRT_MT_NO_REFERENCES, which the GC uses to skip scanning them (replacing the earlier identity check againstcsrt_PrimitiveArray_MT). - Members beyond names and identity (
GetMethods, attributes,Activator, …) come from compile-time metadata for the types the program’s reflection patterns reach (12-corelib.md, ADR 0018).
BigInteger
A BigInteger value is a reference to an immutable uint[] (element 0 the sign, then the
magnitude; null is zero, so default(BigInteger) and zero-initialized arrays are correct). Schoolbook multiplication,
Knuth algorithm D for division (remainder takes the dividend’s sign), exponentiation by squaring,
ModPow, GreatestCommonDivisor, Parse/TryParse, ToString("D"/"N"/"X"), all comparison
operators including the (BigInteger, long) overloads, implicit/explicit conversions, boxing.
Array helpers and sorting
Array.Reverse/Copy/Clear/Fill/IndexOf/Resize/BinarySearch/Empty, andExists/Find/FindIndex/ TrueForAll/ForEachwith predicate delegates (IR loops calling the delegate).Array.Sortis a port of .NET’sArraySortHelper<T>.IntrospectiveSort(src/runtime/bclmisc.c), so the order of elements that compare equal matches the CLR exactly. It is not stable, and .NET isn’t either. Comparers are generated in IR per element type:Comparison<T>delegates andIComparable<T>user types (Comparer<T>.Defaultsemantics, nulls first; structCompareToreceives the element’s address). Primitive arrays use the type’s natural order (double: NaN first).
Culture-sensitive comparison
.NET uses ICU, and so does csharpc: string.Compare, CompareTo, Array.Sort, Comparer<string>,
StringComparer.CurrentCulture/InvariantCulture and StringComparison.*Culture* go through the
ported CompareInfo and ICU’s collator for the culture (corelib/Globalization/CultureStrings.cs;
the runtime’s sorting reaches it through the csrt_string_compare_culture export). With the invariant
culture that is the CLDR root collation, so for example Array.Sort gives "apple" < "Banana".
StringComparison.Ordinal(IgnoreCase) and == stay ordinal; invariant mode makes culture
comparisons ordinal, as in .NET. See 19 — Globalization.
Other members
BitOperations (ctpop/ctlz/cttz/fshl/fshr intrinsics), primitive CompareTo/Equals
(double.CompareTo orders NaN first), double.IsNaN/IsInfinity/IsFinite, generic-math statics
(double.Round, int.Max/Min/Clamp/Abs/Sign, …), Math.Round(double, [digits,] MidpointRounding)
(on the double’s exact decimal value, matching .NET 11), Convert.ToInt32/ToInt64/ToString
with bases 2/8/10/16 and Convert.ToInt32(double) (banker’s rounding), bool.Parse,
Environment.ProcessorCount/TickCount/GetCommandLineArgs/Is64BitProcess,
StringBuilder.Insert/Remove/Replace/indexer/AppendJoin,
string.Concat(string[]), object.ReferenceEquals, x as T
returning null, and custom numeric formats with positive;negative;zero sections.
Formatting and parsing use the provider’s or the current culture’s NumberFormatInfo /
DateTimeFormatInfo (19 — Globalization).
Known gaps
TimeZoneInfo(diagnosed as unsupported, #98);DateTimeOffsetis implemented. Historical daylight-saving gaps take the zone’s current base offset, which can differ from .NET where the standard offset has changed since.- Decimal
Gwith precision follows double-style rules only approximately;decimal.Parsedoes not accept exponents (NumberStyles.Number, as .NET’s default). - Generic type names print as
List1` without arguments. BigIntegeruses O(n²) multiplication and decimal conversion.Array.Sortof arrays of non-comparable reference types, or withIComparer<T>objects.