Our Application is an MVC Application . I tried to run code analysis using ReSharper. I am getting "Auto-property accessor is never used" as warnings in many of my view model properties.
For example, ReSharper shows the warning on this:
public bool IsLegalEntry { get; set; }
Can I make a private setter, or can anybody suggest an alternative?
You could make the setter private
public bool IsLegalEntry { get; private set; }
However, this could cause a runtime error if the setter is used implicitly. Alternatively you could decorate the setter with the JetBrains.Annotations.UsedImplicitlyAttribute.
public bool IsLegalEntry { get; [UsedImplicitly] set; }
Alternative to "warning fixing/suppressing" paradigm, you can add testing project to your solution. Then write a test for you business logic hitting the accessor(s) in question among other things.
Not sure this is the action you were looking for, however
it provides the effect you were after
saves for redundant annotation attributes
adds testing bonus
Related
My team is working on documentation for a robot project. We're currently documenting some camera code but we don't understand some lines.
public Mat Image { get; set; }
public double GyroAngle { get; set; }
Could anyone explain what these lines are doing? If the GyroAngle is simply a double why does it have { get; set; }? Thanks in advance.
It is not strange at all.
A field cannot be used in interfaces but properties can.
Most .NET binding can be done against a property. Not fields
You can change the implementation of a property and keep the contract so no dependent code breaks. For example, in the setter you may add validation. You may not have validation today, but if you do in the future, you can add that. If it was a field, and you change it to property, many bad things will happen such as binary serialization may break.
Some tools will also yell at you if you expose a field as public.
The MSDN has some useful info.
public string FirstName { get; set; } = "Jane";
The class that is shown in the previous example is mutable. Client code can change the values in objects after they are created. In complex classes that contain significant behavior (methods) as well as data, it is often necessary to have public properties. However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties.
What's wrong with
public partial class MainWindow : Window
{
public ObservableCollection<TabViewModel> Tabs { get; set; }
public ICollectionView TabsViewSource { get; set; }
public int CurrentIndex { get { return TabsViewSource.CurrentPosition; } }
I get
Inconsistent accessibility: property type 'System.Collections.ObjectModel.ObservableCollection' is less accessible than property 'TabsRendering.MainWindow.Tabs'
when i change the code to
public partial class MainWindow : Window
{
ObservableCollection<TabViewModel> Tabs { get; set; }
public ICollectionView TabsViewSource { get; set; }
public int CurrentIndex { get { return TabsViewSource.CurrentPosition; } }
It works. Whats wrong with the public on the ObservableCollection
MakeTabViewModela public type too.
Obviously, it doesn't make sense for a public property on a public containing-type to be of a type that is not public. How could the property present itself to external assemblies?
Your second sample works because, as a general rule, providing no accessibility modifiers means that the least applicable modifier is chosen as the default - in this case: private. Clearly, there are no consistency issues with declaring a private property of an internal (?) type.
What's the accessibility on TabViewModel? I'm guessing it's not public.
The message is very straight-forward. It is contradicting to what you want to do. It says you have something declared as public (Tabs, in this case) but the guy who would be using it also need to know about TabViewModel which is not public. Either make both public or some consistent access specifier.
All of the information above is completely correct and works fine. I just want to add from personal experience that if you are using TFS and getting your project from TFS, different Visual Studio versions can also generate this error.
I entered a project with Visual Studio 2013 update 2 and synched with the TFS to get the solution. When I tried to run the project I got 80 errors. All of them were like "... less accessible than property...". Now it turns out I needed update 4. Once my Visual Studio was update I revered the changes and it worked perfectly.
This might be useful if none of the above works and you are using TFS.
I'm writing a library which is shared between .net and silverlight. I have several places where I am doing this, to satisfy the silverlight deserialization (which can't access private members):
[DataMember (IsRequired = true)]
public Object MyProperty { get;
#if SILVERLIGHT
internal
#else
private
#endif
set; }
I know the rules for this, which are that if the setter is private and SILVERLIGHT is defined then the setter should be internal.
Could I use an aspect oriented framework like postsharp to help me reduce this code so that I don't need to specify anything and it will inspect the property, if it has the DataMember attribute and the setter is private, then make the setter internal instead?
Or is there some other technique I could use for this?
EDIT
There seems to be some confusion. My goal is to avoid having the compiler directives at all, but to still have code which is generated with a private member in .net and with a member that can be set by the DataContractDeserializer in Silverlight, which can't access private members. If possible I'd like to automatically modify the property in a silverlight build so it is internal, whilst not having anything other than the DataMember attribute in the source.
Ideally I see the solution being something like:
Write an aspect which checks every property or field.
If the property/field has the [DataMember] attribute then
If the silverlight compiler directive exists then
if the setter is private make it internal (for properties) or if it is declared as private make it internal (for fields)
but I'm not sure which bits of that it would be possible to do using a tool like post sharp.
The other answers either attack the merit of the problem or present alternative approaches that do not directly answer the question. The question was whether there was a way to change the visibility of the setter for a property with a DataMember attribute after it is compiled, to support two versions (.NET and Silverlight).
I suspect the PostSharp SDK would support this. However, this is a problem I had to solve while developing Afterthought, as I needed to change the visibility of anonymous static delegates generated by the C# compiler (normally private until I made them internal). Afterthought itself does not currently support your scenario directly, but it leverages the open source Microsoft CCI libraries, which do. The IL Mutator example shows how to use the CCI libraries to load a compiled assembly and modify it by creating a mutable copy. The example is actually much more complex than your scenario, as you will not be modifying IL, just the visibility of a setter.
This is an example of changing the visibility of a method from within a mutator in CCI:
public override MethodDefinition Mutate(MethodDefinition methodDef)
{
// Automatically make all private static methods to have internal scope
if (methodDef.IsStatic && methodDef.Visibility == TypeMemberVisibility.Private)
methodDef.Visibility = TypeMemberVisibility.Assembly;
This is a slightly simplified excerpt from the Afterthought amender. There are also examples in the same class for how to determine if a method is a setter (starts with set_, HideBySig, etc). You would just need to create a mutator, override the method in this example, verify that the method is a property setter with a DataMember attribute on the containing property definition, and change the visibility.
Simple answer is NO. PostSharp is a Post-Compile framework so you cannot use your compiler directives (as you're trying to do in your question). You can use PostSharp to
Introduce properties into the class with the accessors desired (which doesn't give you access at design time) Directives can be applied to the aspect at design time to determine which property to inject though
Or use reflection to change the accessor (I dont think you can do that)
An alternative is to use T4 templates to generate these classes for you
Edit: Example of property injection
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Strict)]
public class PropInj : InstanceLevelAspect
{
#if SILVERLIGHT
[IntroduceMember(OverrideAction = MemberOverrideAction.Ignore, IsVirtual=true, Visibility=Visibility.FamilyAndAssembly)]
public string MyProperty { get; set; }
#else
[IntroduceMember(OverrideAction = MemberOverrideAction.Ignore, IsVirtual = true, Visibility = Visibility.Private)]
public string MyProperty { get; set; }
#endif
}
[PropInj]
public class test
{
//public int MyProperty { get; set; }
public test()
{
}
}
but really you need to rethink your design.
I know in C# you can easily create accessors to a data type, for example, by doing the following:
public class DCCProbeData
{
public float _linearActual { get; set; }
public float _rotaryActual { get; set; }
}
However my colleague, advised me to do it this way:
public class DCCProbeData
{
private float _linearActual = 0f;
public float LinearActual
{
get { return _linearActual; }
set { _linearActual = value; }
}
private float _rotaryActual = 0f;
public float RotaryActual
{
get { return _rotaryActual; }
set { _rotaryActual = value; }
}
}
My way seems simpler, and more concise. What are the differences and benefits of doing it either way?
Thanks
Edit Just a note, my colleague was able to generate the code for the "second way" using the Refactor option within the Class Details pane most easily found in a Diagram file. This makes it easy to add many Properties without having to manually create the accessors.
"Your way" just tells the compiler to create the second option. Unless you do something else in the getter or setter, they are functionally identical.
However, with "your way", I would recommend using the proper C# naming conventions. I would personally write this as:
public class DccProbeData
{
public float LinearActual { get; set; }
public float RotaryActual { get; set; }
}
The only difference is that you've named the fields.
(I'd stick with your colleagues naming convention for public properties though.)
They do the same thing internally. The only difference is that you cannot directly access the backing field variable using Auto Implemented Properties.
They are technically the same... the get/set is shorthand (auto property).
Lots of questions on SO about this:
When to use get; set; in c#
What is the { get; set; } syntax in C#?
Auto-Implemented Properties c#
Your way doesn't allow you to initialize the values, and your colleague's way follows a more-standard naming convention.
I would like to add something that I haven't seen in the other answers, which makes #2 a better choice:
Using the first method you cannot set a breakpoint on the get and set.
Using the second method you can set a breakpoint on the get and set, which is very helpful for debugging anything accessing your private variable.
Okay, the names have been mentioned before. It's also worth noting that as well as not being with the normal .NET conventions, beginning a public name with an underscore is not CLS-compliant (indeed, one reason for using it for private names is precisely because of this, it makes the distinction clearer, and should result in a warning with some code-checkers if you accidentally have the wrong access level).
Names aside, the one advantage to the latter form is that you can add more complicated code. Still, it's a non-breaking change to go from the former style to the latter, so there's no reason to do it before it's needed.
The first way is the way to go when you need simple properties with get and set and private storage done for you.
Use the second way if you need to do something special when you get or set the value.
Also, I recommend you stick to naming conventions using FxCop or ReSharper.
I believe at the IL level, they both end up the same. In the background, VS creates autonamed variables for you when using the auto getters and setters.
The only way this could possibly be better is if you feel you will be adding more logic to the getters and setters at a later date.
Even then, this seems a little pointless.
They are the same in the sense that your code sample will automatically generate backing fields.
But the two code samples are different because the names of the properties are not the same (LinearActual vs linearActual)
There is no difference, however prior to C# 3 you had to use the long way. At the end of the day it's a C# feature - syntactic sugar. They are both functionally identical.
Things you can do when you don't use auto-implemented properties:
initialize to a default value
access or annotate the backing field (attributes)
read-only backing fields or immutability
set a breakpoint on access
have custom code around access to the variable
Use [System.ComponentModel.EditorBrowsableAttribute()] to enable custom logic on the accessors that you avoid accidently bypassing while coding
hides the backing field from intellisense
Conversion between the two ways is made very simple with ReSharper.
This is not to say don't use them by all means use them, unless you have a need for any of the other functionality listed.
Is there a difference between:
public T RequestedValue { get; set; }
and
public T RequestedValue;
?
Taken from this code:
public class PropertyChangeRequestEventArgs<T>:EventArgs
{
public PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}
public T RequestedValue { get; set; }
}
The first is an Auto-Implemented Property the second is a Field. Regular Properties expose Getters and Setters but have a private field to actually store the value:
private int someProperty;
public int SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
The first allows you to change certain aspects of the implementation of your class without affecting all the other code in your application. The most important point is that, with properties, changes can be made without breaking binary compatibility (although a field can often be changed to a property without breaking code). If it is a public member, a property is advisable. (Stealing shamelessly from Snarfblam's comment)
From the Properties page:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Properties with a backing field are the most flexible form as they allow easy implementation of things like the INotifyPropertyChanged event for updating the UI in Model-View-ViewModel implementations.
deep explanation!
The {get; set;} is an automatic property, while the second is a field.
a field is a normal variable, from some type, that contains data.
a property is a couple of methods (well sometimes it's just one), one for get, and one for set. they only have a syntax like fields, but actually they are quite different.
properties are usually for filtering the set of the value, or virtualizing something in the get, etc.
automatic properties, also create a private field behind the scenes, return its value in the get, and set its value in the set.
seemingly this is just like a normal field, but behind the scenes (IL) using properties is totally different from using fields.
a.Property1 = 4;
is translate into something like:
a.Set_Propert1(4);
and this:
x = a.Property1;
is translate to something like this:
x = a.Get_Property1();
so why is it a good practice to use only public properties, even if they are automatic?
say you are writing a library, that is used by other application, and someday you want to release a new version of that library that constrains one of your class' fields..
if you are using properties, you can just change the property (even if it is an automatic one, you can replace it by a full one), and then any application which used your library can still use it in the same way.
but if you made a public field, which you now want to constrain, you'll need to make a property for this and make the field private, but if you will, any application that used you library will no more be bale to, because the way it use fields and property is different.
You may write:
public T RequestedValue { get; set; }
as a shortcut of:
private T _requestedValue;
public T RequestedValue
{
get { return this._requestedValue; }
set { this._requestedValue = value; }
}
They are totally equivalent, also considering the performance.
The answer is, yes you can remove the { get; set; } but then a whole load subtle differences kick in. Some will say fields and properties express radically different design intent but in practice this distinction has been eroded over the years as C# evolves and progressively blurs the the syntactic differences.
For a good list of compiler-binary level differences between fields and properties refer to SO question difference-between-property-and-field-in-c. But the answers to that question missed one significant point about the special role of properties when declaring interfaces.