Converting null literal or possible null value to non-nullable type

Viewed 31022

Is it possible to resolve this warning:

Converting null literal or possible null value to non-nullable type.

without suppression for this C# code

 List<PropertyInfo> sourceProperties = sourceObject.GetType().GetProperties().ToList<PropertyInfo>();
            List<PropertyInfo> destinationProperties = destinationObject.GetType().GetProperties().ToList<PropertyInfo>();

            foreach (PropertyInfo sourceProperty in sourceProperties)
            {
                if (!Equals(destinationProperties, null))
                {
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
                    PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.

                   
                }
            }

that uses Reflection.

enter image description here

I am using Visual Studio 2019 and .NET Core 3.1.

1 Answers

Find() can return null when what you're looking for is not found. So destinationProperty can become null.

So the solution would be to declare it as nullable:

PropertyInfo? destinationProperty = ...

Or to throw an exception:

PropertyInfo destinationProperty = ...Find() ?? throw new ArgumentException(...)
Related