C
C#9mo ago
Dongle

❔ AOT compatible way of getting the default value of a Type?

Say we have a known Type, what are some AOT compatible options to get the default value of that Type? (note: Reflection is currently okay)
5 Replies
Tvde1
Tvde19mo ago
If you have a generic type parameter T you can default(T). Does that work for you?
Dongle
Dongle9mo ago
No, we don't have the generic type parameter
JakenVeina
JakenVeina9mo ago
Reflection is currently okay
can you not simply have a look at .IsValueType then? if true, you can reflect to grab the parameterless constructor, which is guaranteed to exist for value types, otherwise the default is null
reflectronic
reflectronic9mo ago
public static object? GetDefault(Type type)
{
if (type.IsValueType)
{
return RuntimeHelpers.GetUninitializedObject(type);
}

return null;
}
public static object? GetDefault(Type type)
{
if (type.IsValueType)
{
return RuntimeHelpers.GetUninitializedObject(type);
}

return null;
}
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.