Skip to content
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

Better error message for Response<T> implicit cast from null #25580

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
13 changes: 12 additions & 1 deletion sdk/core/Azure.Core/src/ResponseOfT.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.ComponentModel;
using System.Diagnostics;

Expand Down Expand Up @@ -32,7 +33,17 @@ public abstract class Response<T>
/// Returns the value of this <see cref="Response{T}"/> object.
/// </summary>
/// <param name="response">The <see cref="Response{T}"/> instance.</param>
public static implicit operator T(Response<T> response) => response.Value;
public static implicit operator T(Response<T> response)
{
if (response == null)
{
#pragma warning disable CA1065 // Don't throw from cast operators
throw new ArgumentNullException(nameof(response), $"The implicit cast from Response<{typeof(T)}> to {typeof(T)} failed because the Response<{typeof(T)}> was null.");
#pragma warning restore CA1065
}

return response.Value;
}

/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
Expand Down
11 changes: 11 additions & 0 deletions sdk/core/Azure.Core/tests/ResponseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ public void ValueObtainedFromCast()
Assert.AreEqual("test_name", value.Name);
}

[Test]
public void ImplicitCastFromResponseTToNullFails()
{
Response<string> response = null;
var exception = Assert.Throws<ArgumentNullException>(() =>
{
string s = response;
});
StringAssert.StartsWith("The implicit cast from Response<System.String> to System.String failed because the Response<System.String> was null.", exception.Message);
}

[Test]
public void ToStringsFormatsStatusAndValue()
{
Expand Down