C#: validate Variant before conversion
Nil, Int64, ranges and strict integer acceptance without coercing strings.
When Variant is needed
Variant is a value at dynamic engine boundaries: Get/Set, Call and untyped collections. Keep concrete C# types inside your model. Variant does not make an arbitrary object, List<T> or DateTime engine-compatible.
| Value | Representation |
|---|---|
| default(Variant) | Variant.Type.Nil |
| int, long | Variant.Type.Int; read with AsInt64; Obj is long |
| float, double | Variant.Type.Float; Obj is double |
| int[] | Packed array; AsInt32Array returns a .NET array |
| Resource / Entity | Object reference; lifetime checks still apply |
VariantType reports the actual category. An As… method performs conversion rather than validating a schema. For a strict integer counter, first check Int, then the long range, then convert to int.
A complete validating method
Add this file as an ordinary C# helper; do not attach it to an Entity. TryRead accepts 25 and 999L; it rejects −1L, 1000L, 1L << 40, the string "25", 25.0 and Nil. Failure sets the output to 0. The caller must check the bool before using count.
VariantCounter.cs
using Reckfell;
public static class VariantCounter
{
public static bool TryRead(Variant value, out int count)
{
count = 0;
if (value.VariantType != Variant.Type.Int) return false;
long raw = value.AsInt64();
if (raw < 0 || raw > 999) return false;
count = (int)raw;
return true;
}
}The complete fixture displays 25. This validates one field, not a complete JSON/save schema: keys, message size, required fields and schema versions need separate rules.
Copies and lifetime
You can independently modify the .NET array returned by AsInt32Array: this does not write back into the original Variant. Engine Array/Dictionary follow shared-reference rules instead; see collections.
Variant is a struct implementing IDisposable and can retain native data. Do not arbitrarily dispose a copy while another copy is in use: internal ownership can be shared. Bound the lifetime of a temporary Variant you create; do not dispose borrowed values still used by another owner. Wrapping an Entity in Variant does not keep it alive after Free.