From 274cd6a9b4c91803750f1e6967cf0f96980af9d9 Mon Sep 17 00:00:00 2001 From: Anne Thompson Date: Mon, 11 Sep 2023 13:36:39 -0700 Subject: [PATCH] Don't allow setting Variant to Variant (#38592) * Don't allow setting Variant to Variant * pr fb --- .../src/Variant/Variant.cs | 12 ++++- .../tests/Variant/VariantUsage.cs | 52 +++++++++++++++++++ 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/sdk/core/Azure.Core.Experimental/src/Variant/Variant.cs b/sdk/core/Azure.Core.Experimental/src/Variant/Variant.cs index 68dcf68018da7..ec3264b5edd22 100644 --- a/sdk/core/Azure.Core.Experimental/src/Variant/Variant.cs +++ b/sdk/core/Azure.Core.Experimental/src/Variant/Variant.cs @@ -22,8 +22,16 @@ public readonly partial struct Variant /// public Variant(object? value) { - _object = value; - _union = default; + if (value is Variant variant) + { + _object = variant._object; + _union = variant._union; + } + else + { + _object = value; + _union = default; + } } /// diff --git a/sdk/core/Azure.Core.Experimental/tests/Variant/VariantUsage.cs b/sdk/core/Azure.Core.Experimental/tests/Variant/VariantUsage.cs index ece22ee4e7ca7..3c115b0ae7b66 100644 --- a/sdk/core/Azure.Core.Experimental/tests/Variant/VariantUsage.cs +++ b/sdk/core/Azure.Core.Experimental/tests/Variant/VariantUsage.cs @@ -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 list = new List { "1" }; + // object oa = list; + // object ob = oa; + // list[0] = "2"; + // + // Assert.AreEqual("2", list[0]); + // Assert.AreEqual("2", ((List)oa)[0]); + // Assert.AreEqual("2", ((List)ob)[0]); + // + // Variant should do the same. + // The following test validates this functionality. + + List list = new List { "1" }; + Variant a = new(list); + + Assert.AreEqual("1", list[0]); + Assert.AreEqual("1", a.As>()[0]); + + list[0] = "2"; + + Assert.AreEqual("2", list[0]); + Assert.AreEqual("2", a.As>()[0]); + + Variant b = new(a); + + Assert.AreEqual(a, b); + Assert.AreEqual("2", b.As>()[0]); + + list[0] = "3"; + + Assert.AreEqual("3", list[0]); + Assert.AreEqual("3", a.As>()[0]); + Assert.AreEqual("3", b.As>()[0]); + } + #region Helpers public static IEnumerable VariantValues() {