Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a warning on identity assignment?

I've made this mistake a number of times - it happens when I'm working quickly and using code completion. I end up with code like the following:

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

Then a test fails in a slightly less than obvious way, and I get bummed out.

I'm just curious if there's a valid reason to write code like that, ever, and if not, then does it make for a good candidate to generate a warning?

like image 295
Aaron Anodide Avatar asked May 14 '11 23:05

Aaron Anodide


3 Answers

I'm just curious if there's a valid reason to write code like that, ever

Depending on how you look at, unfortunately yes there is. Because the identifier we are talking about is a property, assigning a property to a property sounds like a no-op but it actually invokes methods, the getter and the setter, and those methods might have side effects.

A specific case that is very common is if the setter does something like property notification or calls an observer but anything could happen when you call either the getter or the setter. This is why the code does not generate a warning: because this coding style is actually useful and used in production code.

Edit:

By comparison, if the identifier is a field and not a property, it does generate this warning:

warning CS1717: Assignment made to same variable; did you mean to assign something else?

like image 191
Rick Sladkey Avatar answered Nov 06 '22 07:11

Rick Sladkey


Use FxCop (aka Code Analysis), it will give you the warning:

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

like image 30
Alex Aza Avatar answered Nov 06 '22 08:11

Alex Aza


Other than "it counts as a valid instruction", there's no reason to ever use this. That said, it's also not wrong: it conforms the syntax for assignment.

If you are writing a code validator, then this is a good candidate for a warning, although of course it should never hamper actual compiling; most compilers already catch this kind of operation during bytecode optimisation, where instructions that do not perform any control logic and don't actually modify registers are removed.

like image 3
Mike 'Pomax' Kamermans Avatar answered Nov 06 '22 09:11

Mike 'Pomax' Kamermans