C
C#15mo 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
Tvde115mo ago
If you have a generic type parameter T you can default(T). Does that work for you?
Dongle
DongleOP15mo ago
No, we don't have the generic type parameter
JakenVeina
JakenVeina15mo 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
reflectronic15mo 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
Accord15mo 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.
Want results from more Discord servers?
Add your server