Skip to content

Don't allow setting Variant to Variant #38592

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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