Skip to content

Commit

Permalink
Fixed array covariance
Browse files Browse the repository at this point in the history
  • Loading branch information
sakno committed Aug 17, 2024
1 parent bd0a56e commit 5cbb4c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/DotNext.Tests/Runtime/ValueReferenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,16 @@ public static void BoxedValueInterop()
Equal(boxedInt.Value, reference.Value);
}

[Fact]
public static void ArrayCovariance()
{
string[] array = ["a", "b"];
Throws<ArrayTypeMismatchException>(() => new ValueReference<object>(array, 0));

var roRef = new ReadOnlyValueReference<object>(array, 1);
Equal("b", roRef.Value);
}

private record class MyClass : IResettable
{
internal static string StaticObject;
Expand Down
13 changes: 13 additions & 0 deletions src/DotNext/Runtime/ValueReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public readonly struct ValueReference<T>(object owner, ref T fieldRef) :
/// </summary>
/// <param name="array">The array.</param>
/// <param name="index">The index of the array element.</param>
/// <exception cref="ArrayTypeMismatchException">
/// <typeparamref name="T"/> is a reference type, and <paramref name="array" /> is not an array of type <typeparamref name="T"/>.
/// </exception>
public ValueReference(T[] array, int index)
: this(array, ref array[index])
{
Expand Down Expand Up @@ -131,6 +134,16 @@ public readonly struct ReadOnlyValueReference<T>(object owner, ref readonly T fi
{
private readonly nint offset = RawData.GetOffset(owner, in fieldRef);

/// <summary>
/// Creates a reference to an array element.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="index">The index of the array element.</param>
public ReadOnlyValueReference(T[] array, int index)
: this(array, in array[index])
{
}

/// <summary>
/// Creates a reference to a static field.
/// </summary>
Expand Down

0 comments on commit 5cbb4c6

Please sign in to comment.