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?
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?
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.
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.
Related
This might be a silly question. I know that compiler will remove unused locals. But if I write my code like this:
class MyClass
{
public int SomeProperty
{
get
{
...
}
}
public void SomeFunction ()
{
//will this line be removed if i is never used?
int i = SomeProperty;
...
}
}
I am wondering that if i will be removed by compiler because of optimization. There is logic inside the getter of SomeProperty that I wish to execute. If i will be removed, I have to change SomeProperty to a function.
Btw, is there a way to know which line will be optimized by compiler?
I would suggest that what the compiler does is not important. This is bad design.
If calling a getter has important side effects then it should probably not be a getter. The most a getter should probably be doing is lazy initialising something and this shouldn't be important since if it doesn't happen it will just get done by the next thing to get it.
I don't know what you are doing but it probably should be refactored into its own method that can be called explicitly at that point.
The other major concern is relate to readability. Anybody seeing the line int i = SomeProperty; when i is never used again might well decide that the line is pointless and does nothing and thus remove it from the code causing whatever unexpected errors to arise. You would be better off calling a method like LogicExtractedFromProperty() so it is obvious you are doing something.
The compiler might (or might not, I don't know or care) do the right thing but a person may well not.
My answer to one of the question on SO was commented by Valentin Kuzub, who argues that inlining a property by JIT compiler will cause the reflection to stop working.
The case is as follows:
class Foo
{
public string Bar { get; set; }
public void Fuzz<T>(Expression<Func<T>> lambda)
{
}
}
Fuzz(x => x.Bar);
Fuzz function accepts a lambda expression and uses reflection to find the property. It is a common practice in MVC in HtmlHelper extensions.
I don't think that the reflection will stop working even if the Bar property gets inlined, as it is a call to Bar that will be inlined and typeof(Foo).GetProperty("Bar") will still return a valid PropertyInfo.
Could you confirm this please or my understanding of method inlining is wrong?
JIT compiler operates at runtime and it can't rewrite metadata information stored in the assembly. And reflection reads assembly to access this metadata. So there are no impact from JIT-compiler to reflection.
EDIT:
Actually there are couple of places when C# compiler itself "inlines" some information during compilation. For example, constants, enums and default arguments are "inlined" so you can't access them during reflection. But it definitely not related to your particular case.
Yeah when I think about it more I guess only way inlining properties could fail INotifyPropertyChanged interface correct work would be if you were using a reflection based method used like
public Count
{
get {return m_Count;}
set { m_Count=value;
GetCurrentPropertyNameUsingReflectionAndNotifyItChanged();}
}
If used like you suggest indeed metadata exists in assembly and property name will be successfully taken from there.
Got us both thinking though.
I personally agree with #Sergey:
Considering that inlining happens on JIT compiler side, but metadata generated before, it shouldn't inpact on reflection in any way. By the way, good question, like it +1
Expression trees can't be in-lined anyway since they are a representation of the expression (abstract syntax tree) rather than the expression itself.
Delegates, even if they can be in-lined, will still carry the data about the method and target being called in their properties.
Say, for example, I've got this simple class:
public class MyClass
{
public String MyProperty { get; set; }
}
The way to get the PropertyInfo for MyProperty would be:
typeof(MyClass).GetProperty("MyProperty");
This sucks!
Why? Easy: it will break as soon as I change the Name of the Property, it needs a lot of dedicated tests to find every location where a property is used like this, refactoring and usage trees are unable to find these kinds of access.
Ain't there any way to properly access a property? Something, that is validated on compile time?
I'd love a command like this:
propertyof(MyClass.MyProperty);
The closest you can come at the moment is to use an expression tree:
GetProperty<MyClass>(x => x.MyProperty)
and then suck the PropertyInfo out in GetProperty (which you'd have to write). However, that's somewhat brittle - there's no compile-time guarantee that the expression tree is only a property access.
Another alternative is to keep the property names that you're using somewhere that can be unit tested easily, and rely on that.
Basically what you want is the mythical infoof operator which has been talked about many times by the C# team - but which hasn't made the cut thus far :(
In the time since this question was posted, C# 6 has been released with the nameof operator. This allows a property to be accessed with the following
PropertyInfo myPropertyInfo = typeof(MyClass).GetProperty(nameof(MyClass.MyProperty));
If you rename the property, this code will not compile (actually it will, since the rename will change this line of code as well if the rename is done properly).
The whole point of reflection is to be able to access stuff at runtime. If we assume your operator would work, you already have the class information and thus the property, making the whole thing completely useless.
If I am accessing a member field, property, or method, I'm never sure when I should prepend it with 'this'.
I am not asking about cases where it is required, like in the case where a local variable has the same name. I am talking about cases where the meaning is exactly the same. Which is more readable? Are there any standards, best practices, or rules of thumb I should be following? Should it just be consistent throughout a class, or an entire code base?
I disagree with StyleCop on this one, and I'm not even sure that StyleCop's opinion should be interpreted as an official Microsoft guideline anyway. It was an internal tool used at Microsoft but not all teams use it, and not all teams use all the rules.
Adding this everywhere is not necessary and often just adds clutter. It does not improve performance and I'm not convinced that adding this all over the code improves readability either.
You might hear arguments that it makes it more clear where the variable is defined, but I would argue that if your class/method is so long and complicated that it is difficult to work out where something is declared then you probably should refactor it anyway. If you use the single responsibility rule and have short functions it should be obvious whether a variable is a member, a function parameter or a local variable.
As you point out, sometimes it is necessary. For example in the constructor if you want to set a private member with the same name as the parameter.
public class Foo
{
private Bar bar;
public Foo(Bar bar)
{
this.bar = bar;
}
}
I recommend using Microsoft's guidelines, as verified by StyleCop: http://blogs.msdn.com/sourceanalysis/
The general rule is, prepend members with "this." when they are defined in the class, unless they are static, in which case you cannot.
Here is the rule directly from StyleCop:
SA1101: The call to {method or property name} must begin with the
'this.' prefix to indicate that the item is a member of the class.
I would say avoid as much as possible, it saves you some(in fact a lot of) typing.
I would depend on Visual Studio more to help me to find where what belongs(never forget F12). I don't use notepad to read my cs files :P
If you follow Microsoft's StyleCop, you should always use prefix class members with the this keyword.
SA1101: PrefixLocalCallsWithThis
TypeName: PrefixLocalCallsWithThis
CheckId: SA1101 Category: Readability Rules
Here's a similar StackOverflow question on the same topic.
I usually access parameters on the current object with this. Given a naming convention for instance variables "m_", this makes it easy to see at a glance what is affected by following statements without knowing their context:
m_Height += 10; // an instance variable
height += 10; // a local variable
this.Height += 10; // a property
In my code, I only use this.<PropertyName> when the property is a member of a base class, not the class I'm currently in.
Of course, not using 'this' at all is another popular choice, since it's unnecessary code being added.
Our coding standards at work state that member variables shouldn't be prefixed with 'm' or'_' or whatever else most people use. I've actually found myself using this.memberVariable all the time. I prefer the clarity over a little extra typing. And as mentioned in other answers, it's necessary when referencing parameters with the same name as member variables.
If you're using Visual Studio and Intellisense. When you type this you get a list of just your class level variables methods etc. Leaving out all the other possible items.
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?
Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.
Thanks
It's for clarity and to prevent any ambiguity between a class member and a local variable or parameter with the same name.
The IL it compiles to will not be any different.
Most of the time is just for clarity but some times it is required.
using System;
class Foo
{
String bar;
public Foo(String bar)
{
this.bar = bar;
}
}
Here you will need this as it serves to disambiguate between the field bar and the constructor parameter bar. Obviously changing the name of the parameter or field could accomplish the same thing.
In all cases, there is no performance difference with/without the this - the compiler still does it implicitly, injecting a ldarg.0 into the IL.
Just for completeness, there is one other mandatory use of this (excluding disambiguation, ctor-chaining, and passing this to other methods): extension methods. To call an extension method on the current instance, you must qualify with this (even though for a regular method it would be implicit).
Of course, in most cases, you would simply add a regular instance method to the class or a base-class...
class Foo {
void Test() {
this.Bar(); // fine
Bar(); // compiler error
}
}
static class FooExt {
public static void Bar(this Foo foo) { }
}
In C# this is a reference to the current instance of the class (it's me in VB.NET). It's used generally to fully qualify a class member. For example, consider this C# class:
public class MyClass
{
int rate;
private void testMethod()
{
int x;
x = this.rate;
}
}
this isn't required in the code above, but adds instant clarity when reading the code that rate belongs to the class rather than the method (search SO, you'll find lots of opinions about the use of this). It's semantic behavior is the same in VB--and its use doesn't impose a performance penalty.
Apart from the clarity examples provided the only other valid usage of the "this" keyword is to pass the current instance of an object as a paremeter.
It is just for clarity, and one can argue about what is better. Python doesn't support omitting the "self" identifier at all.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET?
In JVM for sure (and also for CLR, I'm almost sure) the code for the "this" keyword is always generated, even if that is omitted from the source - so it's like if the this keyword is always added. So, I don't think that any .NET compiler could generate different output, so there can't be a performance penalty.
Then, it depends on the language. For instance JScript (and even JScript.NET) does not allow to omit "this", like Python, because there are functions (so "this.a()" is a method invocation, "a()" is a function invocation), and because the compiler does not know the members of any types - they're only known at runtime (well, this is not an impossible problem to solve indeed, the other issue is more relevant).