AvoidUse attribute: do not use this member! #113355
Replies: 1 comment
-
This is a language discussion, not for runtime.
This is not the case. All of the popular JSON serialization library supports populating fields in constructor.
This is a well-known usage of
There is |
Beta Was this translation helpful? Give feedback.
-
The problem
My proposal is to create an attribute to limit the use of a public API, but not make it inaccessible in the assembly hiding or defining it private or friend-access. Something similar to what we have for the ExperimentalAttribute and ObsoleteAttribute, but used when the member must exist, is not experimental and is also not deprecated, but was not made for public use and instead to satisfy an internal condition or use.
Let's consider a use case: I have a class that has two different constructors, and I need this class to be created with one of those constructors when used by the public API. The problem is that this class needs to be serialized and deserialized by JSON, so a public parameterless constructor is required. However, this constructor would be a logical error in the API, with uninitialized members or behavior not expected by the other two constructors. Therefore, we would have an attribute indicating that this constructor should not be used.
Above, the code works well with the
ObsoleteAttribute
, but as I said, this constructor is not obsolete, and it would also not make sense to use Experimental because it is not experimental.The solution
My proposal is for an attribute named "AvoidUsage" (or something similar), which would have the same behavior as the ExperimentalAttribute (I need to suppress the warning to use the member).
And when trying to construct it, the compiler should emit an error:
You could still continue and use the constructor if you suppress the warning:
Also, having a property to "hide" this member from auto-complete, such as Intellisense, would be interesting. This solution would bring more meaning to the code, and make it clear that this member must exist, but not be used without reading the reason it is hidden. This brings more confidence in situations where there is no certainty that this member will be used improperly and prevents future problems.
Beta Was this translation helpful? Give feedback.
All reactions