mardi 8 février 2022

C# Reflection- using FieldInfo.SetValue to set a struct field to null safe?

If you use C# reflection to set a (non-nullable) value-type field to null, it appears to accept that and just sets the default value. But since this behavior is slightly unexpected (I'd expect an exception) and I can't find any docs describing this behavior, I want to know if this is safe. Or am I relying on some undocumented / undefined behavior?

Example:

using System;
using System.Reflection;
                    
public class Program
{
    public static void Main()
    {
        FieldInfo pointField = (typeof(ClassWithAPoint)).GetField("point");
        
        ClassWithAPoint classWithAPoint = new ClassWithAPoint();
        classWithAPoint.point.x = 1;
        classWithAPoint.point.y = 2;

        //This works to create a default Point struct (0, 0).  But is this safe?
        pointField.SetValue(classWithAPoint, null);
        
        
        //Prints: "Point = 0, 0"
        Console.WriteLine($"Point = {classWithAPoint.point.x}, {classWithAPoint.point.y}");
    }
    
    public struct Point
    {
        public int x;
        public int y;
    }
    
    public class ClassWithAPoint
    {
        public Point point;
    }
}




Aucun commentaire:

Enregistrer un commentaire