#
Type Casting
h5 provides robust support for C# type casting operations in JavaScript.
#
is and as Operators
You can use the is and as operators to check type compatibility and cast between types at runtime.
public void Process(object obj)
{
if (obj is string s)
{
Console.WriteLine("String: " + s);
}
else if (obj is int i)
{
Console.WriteLine("Int: " + i);
}
var list = obj as IList<string>;
if (list != null)
{
Console.WriteLine("List count: " + list.Count);
}
}
h5 generates JavaScript code that checks the constructor and prototype chain of the object to determine compatibility.
#
[Cast] and [IgnoreCast] Attributes
You can control how casting operations are translated using attributes.
#
[Cast] Attribute
The [Cast] attribute allows you to specify a custom casting implementation.
[External]
[Cast("parseInt({0})")]
public static extern int ToInt(object value);
#
[IgnoreCast] Attribute
Sometimes you want to treat an object as a specific type without any runtime checks or conversion logic, purely for the compiler's benefit (compile-time casting). This is common when working with dynamic JavaScript objects or generic wrappers.
The [IgnoreCast] attribute tells the compiler to emit the casted expression directly, without wrapping it in a type check or conversion function.
[IgnoreCast]
public T As<T>()
{
return (T)(object)this;
}
// Usage
var result = myObj.As<int>();
When compiled, myObj.As<int>() simply becomes myObj in JavaScript.
#
Runtime Checks
By default, explicit casts (T)obj will throw an InvalidCastException if the cast is invalid at runtime, just like in .NET.
object o = "hello";
int i = (int)o; // Throws InvalidCastException
To avoid runtime overhead in performance-critical code where you are certain of the types, you can disable these checks globally in h5.json using the ignoreCast option, or locally with [IgnoreCast].