How can I check if a generic method parameter is a value type? [duplicate]
-
06-02-2021 - |
Question
Is there a way to check if a variable is value type of reference type?
Imagine:
private object GetSomething<T>(params T[] values)
{
foreach (var value in values)
{
bool is ValueType; // Check if 'value' is a value type or reference type
}
}
Solution
bool isValueType = typeof(T).IsValueType;
Job done... it doesn't matter if any of the values is null
, and it works even for an empty array.
OTHER TIPS
Your condition will look like
var cond = false;
if(value != null)
cond = value.GetType().IsValueType
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow