C
C#2y 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
Tvde12y ago
If you have a generic type parameter T you can default(T). Does that work for you?
Dongle
DongleOP2y ago
No, we don't have the generic type parameter
JakenVeina
JakenVeina2y 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
reflectronic2y 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
Accord2y 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.

Did you find this page helpful?