Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting type definition for nullable types breaks code for non-nullable types

This is a follow-up question to the following if you would like to see: Parse to Nullable Enum

Type t = currentProperty.PropertyType;
if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
    t = t.GetGenericArguments().First();

I am getting an error on line #2 which is the IF statement.

System.Reflection.TargetInvocationException : Exception has been thrown by the 
target of an invocation. ----> System.InvalidOperationException : This operation 
is only valid on generic types.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)

How can I test for that condition before executing the code in the IF statement?

like image 590
Valamas Avatar asked Jul 16 '26 09:07

Valamas


1 Answers

Here is the MSDN documentation on checking for nullable types

It looks like you need to add the following:

if(t.IsGenericType && ...
like image 134
Justin Pihony Avatar answered Jul 18 '26 21:07

Justin Pihony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!