Is this really a simplification? - c#

So I have a pretty simple class with an Id field, and the Id can be set in the constructor.
Typically I will use this to clearly identify the class property as opposed to the method argument. To me this seems clearer.
IDE0003 wants me to remove the this, with the message 'Name can be simplified', is that correct?
This seems less clear to me, and also allows a casing error to easily result in id = id.

This other question has an answer that says you can configure the editor to remove the behavior. Personally I like "this"
Tools > Options > Text Editor > C# > Code Style and check Qualify member access with 'this'
Visual Studio 2015 - Change Light Bulb, Quick Action settings

The this keyword almost always is unnecessary, see When do you use the "this" keyword?.
allows a casing error to easily result in id = id
That will yield another warning on its own:
Assignment made to same variable; did you mean to assign something else?

If you use General Naming Conventions then the this keyword is redundant because the parameter should be id and the property should be Id based on Naming Guidelines. So it seems clear:
public int Id
{
get;
private set;
}
public VSOMessage(int id)
{
Id = id;
}
Please note that the guidelines itself don't say, to use or not use this keyword but because C# is case sensitive, it would be a simplification to remove this keyword but when you don't use Naming Conventions then you may naming the property id instead ofId so you should use this keyword in such cases.

If you want to prevent the warning in code rather then updating Visual Studio settings, use the SuppressMessage data annotation, which will prevent the warning.
It looks something like this:
[SuppressMessage("Reason #Enter whatever you'd like", "ID, must match what intellsense is showing it looks something like this: IDE0001", Justification = "(optional, your own description")]
Here is an exact example for your "this" variable situation:
[SuppressMessage("IntelliSenseCorrection", "IDE0003", Justification = "Allowing usage of 'this' keyword to maintain consistency/readability of code.")]

Related

Why property does not use the same name for backing field in this compiler generated code?

Why is the code below using a string_1 instead of straight using FileName?
And when would compiler generate code? What kind of source code or configuration of compiler (or anything else) would cause the [compiler generated] attribute?
[CompilerGenerated]
private string string_1;
public string FileName
{
[CompilerGenerated]
get
{
return string_1;
}
[CompilerGenerated]
private set
{
string_1 = value;
}
}
When you decompile auto properties of C# classes, you simply see this kind of pattern. The actual name string_1 is chosen by the decompilation engine, and different engines choose different ways to pick up such names.
You can read this article to learn more about decompilation of different C# syntax elements.
Update:
As the comments under this answer illustrated, there are several important spots in this code snippet that reveal more information than themselves,
The name string_1 is a common indicator of decompilation result from an obfuscated assembly through de-obfuscation process. Obfuscation removes the original *__BackingField names, and de-obfuscation adds back such type name_index names.
The missing DebuggerBrowsableAttribute attribute is usually the result of obfuscation (as de-obfuscation usually don't add such back).
Luckily the obfuscation process didn't remove the whole auto property pattern, so you can still tell what it might look like originally.
Note that most obfuscation tools can remove properties and leave behind only fields and methods.

Add code to C# get/set of property without needing backing field?

You know how you can have a property that automatically generates a backing field? Like if I go:
public String SomeProperty {get; set;}
I know that if I want to add code to that property I have to create the backing field as so:
public string someProperty = string.Empty;
public string SomeProperty
{
get { return someProperty; }
set
{
someProperty = value;
DoSomething();
}
}
Basically, what I want to know is... is there any way to do this but without having to create the backing field? For example I could use it to trigger some kind of event that occurs when a property is set. I'm looking for something like this:
public string SomeProperty
{
get;
set { this.OnSomeEvent; }
}
But I know that'll cause a compile error because get needs do declare a body if set does.
I've researched and I cant find anything, but I thought I'd check to see if anyone knew.
I guess what I'm really after is some way to trigger an event when a property is changed but without having to add all that extra clutter. Any suggestions?
Simple answer is no, you can't have it both ways. From .NET Docs:
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.
There are not any solutions for this built into the framework, and you cannot modify existing types via reflection (in order to add the logic at runtime). The only way to accomplish this seems to be at compile time.
There is a product http://www.postsharp.net/ that can accomplish this (intercept property/method calls), and there does appear to be a free edition.
The field keyword might be added to C#, see https://github.com/dotnet/csharplang/issues/140, which removes "when no additional logic" requirement for auto properties.
It didn't make it into C# 10 nor 11, but latest comment from compiler team says C# version 12 might have it. They release yearly, so that would be Nov 2023.

Ignore ReSharper naming rules for DTOs

I have ReSharper naming rules set up such that all property names must be PascalCase. However there are times when I have to use a different naming style to work with serialization. For example, backbone.js expects objects to have an Id named 'id'.
I'd prefer to have my objects match the expectations of serializers rather than use fancy serialization attributes to change the way things are named. Is there a way to mark my DTO classes as such so resharper doesn't complain about them? What about a conventions-based approach, like "Exempt any class whose name ends with 'Dto' or is in a namespace called 'Dto'? Additionally, I'd rather not use the special //disable rule XX comment blocks. I find them really distracting
public class PersonDto
{
public int id {get;set;} //i want resharper to accept this as a valid name,
// but only in this context.
public string Name {get;set;}
public string _CID {get;set;} //some external api is sending me data named like this
}
You can disable inspection for any files. In the Resharper options, go to Code Inspection: Settings and click on "Edit Items to Skip". Add *.DTO.cs to the "File masks to skip" list.

Workaround for Reflection Bug in Dotfuscator?

Greetings all,
I am calling Type.GetProperties(), but after running Dotfuscator, it is returning zero items, when it returned more than zero before.
public class Test
{
public int Number { get; set; }
public void ShowInfo()
{
Type type = this.GetType();
PropertyInfo[] props = type.GetProperties();
Console.WriteLine("type [" + type.Name + "] props count: " + props.Length);
}
}
If I exclude the "Number" property from renaming within Dotfuscator, then it works, but otherwise it doesn't. However, it is not possible for me to do this for all properties in my project, as it would lead to possible bugs.
Are there any workarounds for this method? Or even other "free" obfuscation applications I could use?
I have already tried looking on their website to submit a bug, but I am only using the community edition so there doesn't seem to be as much support for it.
Dotfuscator automatically strips properties (which are just metadata anyway - the real work is done by the get/set pair of methods that are automatically created) during renaming. It also renames the underlying get/set methods as well. Depending on what you are trying to do, you'll need to exclude either the property metadata itself, or the get/set methods (or possibly both) from renaming.
If you need to keep the property metadata intact (for example, to simply list the properties in a Type), you can instruct Dotfuscator to exclude properties from renaming by checking them in the tree view on the Renaming Exclusions tab or using a custom regex property rule. This will only exclude the property metadata - the get/set methods will still be renamed.
If you need to keep the get/set methods (because, for example, you are trying to get or set a property's value by reflection), you can instruct Dotfuscator to exclude those methods from renaming by expanding the property in the tree view and checking the get/set methods underneath, or by using a custom regex method rule.
As the process of obfuscation is not limited to renaming your class members, you can't be sure of that. That's the problem with obfuscation: You basically can't make any assumptions about your class anymore regarding the result of reflection. The only way I can think of is to not use reflection but expressions.
Have a look at this question and its answer to know, what I mean with "expressions": How to raise PropertyChanged event without using string name

CA1726: FxCop Forbidden Word: Flags

someone wants me to make other people's code compliant to some FxCop ruleset which includes rule CA1726:Use preferred terms. Most of the terms/replacements are all right and I can understand that one has to decide on one single way to name things.
However, what's the deal with the term 'flags'? Can anyone explain to me why I shall not use this name? (before I go and complain about it at my boss ;) )
Say, I have a data object which has a member of class 'flags' which bundles a large number of properties that define how to handle the data object. How else would you call this?
In the book Framework Design Guidelines, which is what FxCop is based on, the authors say that using Flag or Flags is a bad idea. Their alternative suggestion is that when naming enumerations that you use a singular name for standard enums and a plural name for bit field (flags) enums.
For example if you wanted to create an enum listing different visibilities then you would name it Visibilities instead of VisibilityFlags or Visibility:
[Flags]
public enum Visibilities {
Public,
Private
}
The only items considered flags in .NET by the authors are these bitfield enumerations due to the keyword Flags attribute.
I would say that the property should be named aptly, and that the term Flags characterises the property rather than describing it.
Flag or Flags | There is no replacement term. Do not use.
For instance, Flags is generally used with enumerations (that are decorated with the appropriate attribute) and we certainly don't need to explicitly state so within the name / identifier of a property:
[Flags]
enum StorageMode
{
None = 0,
Next = 1,
...
Last = 32
}
class StorableItem
{
public StorageMode StorageMode { get; set; }
}
But, in your case, I get the feeling that whatever is named, or contains within its name, Flags, isn't actually a set of flags in the above sense - which just brings up another reason as to why to avoid it.

Categories