Skip to content

Commit

Permalink
Don't allow setting Variant to Variant (Azure#38592)
Browse files Browse the repository at this point in the history
* Don't allow setting Variant to Variant

* pr fb
  • Loading branch information
annelo-msft authored and yaotongms committed Oct 12, 2023
1 parent 032d671 commit 274cd6a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
12 changes: 10 additions & 2 deletions sdk/core/Azure.Core.Experimental/src/Variant/Variant.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,16 @@ public readonly partial struct Variant
/// <param name="value"></param>
public Variant(object? value)
{
_object = value;
_union = default;
if (value is Variant variant)
{
_object = variant._object;
_union = variant._union;
}
else
{
_object = value;
_union = default;
}
}

/// <summary>
Expand Down
52 changes: 52 additions & 0 deletions sdk/core/Azure.Core.Experimental/tests/Variant/VariantUsage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,58 @@ public void CanGetAsString(Variant v, Variant s)
Assert.AreEqual(value, v.ToString());
}

[Test]
public void VariantDoesntStoreVariant()
{
Variant a = new("hi");
Variant b = new(a);

Assert.AreEqual(a, b);
Assert.AreEqual(typeof(string), b.Type);
}

[Test]
public void VariantAssignmentHasReferenceSemantics()
{
// Variant should use reference semantics with reference types
// so that it behaves like object in these cases.
//
// e.g. since:
// List<string> list = new List<string> { "1" };
// object oa = list;
// object ob = oa;
// list[0] = "2";
//
// Assert.AreEqual("2", list[0]);
// Assert.AreEqual("2", ((List<string>)oa)[0]);
// Assert.AreEqual("2", ((List<string>)ob)[0]);
//
// Variant should do the same.
// The following test validates this functionality.

List<string> list = new List<string> { "1" };
Variant a = new(list);

Assert.AreEqual("1", list[0]);
Assert.AreEqual("1", a.As<List<string>>()[0]);

list[0] = "2";

Assert.AreEqual("2", list[0]);
Assert.AreEqual("2", a.As<List<string>>()[0]);

Variant b = new(a);

Assert.AreEqual(a, b);
Assert.AreEqual("2", b.As<List<string>>()[0]);

list[0] = "3";

Assert.AreEqual("3", list[0]);
Assert.AreEqual("3", a.As<List<string>>()[0]);
Assert.AreEqual("3", b.As<List<string>>()[0]);
}

#region Helpers
public static IEnumerable<Variant[]> VariantValues()
{
Expand Down

0 comments on commit 274cd6a

Please sign in to comment.