Why is there no warning about the appointment of an individual?

I made this error several times - this happens when I work fast and use code completion. I get the code as follows:

public class Model : IModel { public PropertyNames PropertyNames { get; set; } public Model(PropertyNames propertyNames) { PropertyNames = PropertyNames; } } 

Then the test fails in a slightly less obvious way, and I get an error message.

I'm just wondering if there is a good reason to write such code, ever, and if not, does it make a good candidate for creating a warning?

+7
source share
3 answers

Use FxCop (aka Code Analysis), this will give you a warning:

Warning 3 CA1801: Microsoft.Usage: The "PropertiesNames" parameter in "Model.Model (string)" is never used. Remove the parameter or use it in the body of the method.

+3
source

I'm just curious if there is a good reason to write such code ever

Depending on how you look, unfortunately, yes, there is. Since the identifier that we are talking about is a property, assigning a property to a property sounds inactive, but actually calls methods, a getter and setter, and these methods can have side effects.

A special case, which is very common, is when the installer does something like a property notification or calls an observer, but anything can happen when you call either the receiver or the installer. This is why code does not generate a warning: because this coding style is really useful and used in working code.

Edit:

For comparison, if the identifier is a field and not a property, it generates this warning:

warning CS1717: assignment to the same variable; Did you want to assign something else?

+6
source

Besides the fact that β€œit is considered a valid instruction”, there is no reason to ever use this. However, this is also not the case: it matches the destination syntax.

If you are writing a code checker, then this is a good candidate for a warning, although, of course, it should never hinder the actual compilation; most compilers already catch this operation during bytecode optimization, where instructions that do not execute any control logic and actually do not change the registers are deleted.

+3
source

Source: https://habr.com/ru/post/888135/


All Articles