Home > OS >  Force inheritance of attribute in C#
Force inheritance of attribute in C#

Time:10-15

I have interface as below:

public interface IError
{
    [JsonPropertyName("error")]
    string Error { get; }

    [JsonIgnore(Condition = JsonIgnoreCondition.Always)]
    int StatusCode { get; }
}

And class that inherits this interface:

public class InvalidClient : IError
{
    public string Error => "invalid_client";
    public int StatusCode => (int)HttpStatusCode.Unauthorized;
}

problem is that JsonIgnore attribute isn't inherited. I want to force inheritance of this attribute, but is this possible? I can't create new attribute that inherites from JsonIgnore, because it's sealed class.

CodePudding user response:

I believe this is a duplicate of this question, where the answer is "this isn't possible."

There's a linked blog post that says

Implicit implementation (as seen above) is when a class implements the method/property in question as a public method or property on the class. It's important to note that this method/property is NOT the same thing as the interface method/property; it merely has the same signature, and thus can be used to implicitly create the implementation of the interface. In reflection terms, the two are distinct and different. Any metadata attached to the interface method or property is not attached to the class method or property, because of this difference.

...

The simple work-around is to convert your model interfaces into abstract classes so that they can inherit the attributes appropriately. If this isn't feasible, then you will have to resort to putting the attributes on the concrete classes instead of the interfaces.

Note that for the above implementation, if you convert to an abstract class, the compiler will warn that you are overwriting the base implementation,

public string Error => "invalid_client";

which will have the same error that the attributes are not "copied" to the child class.

One workaround in your situation is to cast to the interface type.

static void Main(string[] args)
{
    var c = new InvalidClient();

    var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault };
    var json = JsonSerializer.Serialize((IError)c, options);

    Console.WriteLine(json);
}

console out:

{"error":"invalid_client"}
  • Related