Description
Description
The behavior of refStructValue is object
and typeof(object).IsAssignableFrom(typeof(RefStruct))
(where ref struct RefStruct {}
) don't match.
I'm not 100% sure if this is a bug since technically, all types inherit from System.Object
, so the reflection approach is technically correct.
However, in practice, instances can't be cast to that type, as that would box which is against the rules of ref struct
.
Also, Type.IsAssignableFrom(Type)
documentation says:
Determines whether an instance of a specified type
c
can be assigned to a variable of the current type.
An instance of type RefStruct
can't be assigned to variables of object
, so using the API summary is wrong.
Checking pointers, which can't also be cast to object
, the operation typeof(object).IsAssignableTo(typeof(void*))
returns false
(unlike with ref struct which is true
), a value that I would expect as pointers can't be cast to objects.
So, from my point of view, either the API has a bug or the documentation is outdated.
By the way, this also applies to Type.IsAssignableTo(Type)
.
Reproduction Steps
using System;
Console.WriteLine(typeof(object).IsAssignableFrom(typeof(RefStruct)));
Console.WriteLine(new RefStruct() is object);
Console.WriteLine(typeof(object).IsAssignableFrom(typeof(void*)));
ref struct RefStruct { }
Expected behavior
using System;
Console.WriteLine(typeof(object).IsAssignableFrom(typeof(RefStruct))); // false
Console.WriteLine(new RefStruct() is object); // false
Console.WriteLine(typeof(object).IsAssignableFrom(typeof(void*))); // false
ref struct RefStruct { }
Actual behavior
using System;
Console.WriteLine(typeof(object).IsAssignableFrom(typeof(RefStruct))); // true
Console.WriteLine(new RefStruct() is object); // false
Console.WriteLine(typeof(object).IsAssignableFrom(typeof(void*))); // false
ref struct RefStruct { }
Regression?
No idea, though I guess the discrepancy appeared exactly after the invention of ref struct
types.
Known Workarounds
I could check for typeof(RefStruct).IsByRefLike
before using Type.IsAssignableFrom(Type)
.
Configuration
.NET 9
Windows 10 Pro Version 2009 Compilation of OS 19045.5608
X64
Probably happens in all configurations. It also happens in Sharplab.
Other information
No response