Resharper Auto Property implement without method bodies - c#

I'm using the latest ReSharper - 9. I also have StyleCop installed as well.
When I implement an interface with properties it does this:
public class MyClass : IMyClass
{
public bool MyProperty
{
get
{
}
set
{
}
}
}
I want it to implement like this:
public class MyClass : IMyClass
{
public bool MyProperty { get; set; }
}
Exactly how do I set this up?

I had a similar thing happen on Resharper 9, and I found this related bug in the Resharper issue tracker. Installing the update fixed it for me. Also you could try the Alt + Insert workaround as mentioned on that bug.

You should mark the setting from the screenshot

When you tell ReSharper to 'Implement Missing Members', there's a dropdown in the form that appears called 'Properties As:'. If you set this to Automatic property, it will generate properties in the manner you want them to. It looks like you currently have it set to 'Property with backing field'.
Create an interface with a property
Create a class to implement that interface
Move your cursor onto the class declaration line
Press Alt + Enter, and choose 'Implement Missing Members'
On the form that appears, set 'Properties As:' to 'Automatic property'
Press 'Finish'
Bask in your single line Auto Properties.

Related

Mask inherited public property [duplicate]

Is this the way to hide properties in derived controls?
public class NewButton : Button
...
[Browsable ( false )]
public new ContentAlignment TextAlign { get; set; }
Also this hides the property in the Properties window in the designer but how can I also hide the property in code?
From code, the closest you can do it to hide it, and perhaps make it a pain to call directly - note that even when hidden it is callable, and none of this will work past a cast:
// about the closest you can do, but not really an answer
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("just cast me to avoid all this hiding...", true)]
public new ContentAlignment TextAlign { get; set; }
Personally, I wouldn't bother. It isn't robust (just cast).
You can use the [EditorBrowsable] attribute, as documented here.
[EditorBrowsable(EditorBrowsableState.Never)]
public bool HideMeInIntellisense
{
// ...
From the documentation:
...the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.
However, users can override this in VS settings. ReSharper also has a setting that controls whether this attribute is honoured in its IntelliSense.
Out of curiousity, why do you want to hide something from users? Just because a member is hidden in the way described above doesn't mean you couldn't use it in code and compile it successfully. It just inhibits the discoverability of the member.
No, you can remove them from the designer (as shown) but you cannot really hide them form code as that would violate the substitution principle. It has been asked & answered many times here, see for example this SO question.
Maybe what you want to do is derive from ContainerControl or UserControl, add a Button to that control and just expose those parts of the Button interface you want to keep.
Why don't you make it private? It guarantees that ancestors will not see it.
Edit:
In this case you have to inherit a new class from the base and use your new class, which now hides ths property.
public class MyTextBox: TextBox
{
...
private new ContentAlignment TextAlign
{
get { return base.ContentAlignment; }
set { base.ContentAlignment = value; }
}
}

What is the best way to restrict method access at compile time?

Let's say I have a Manager class
public class Manager {
public Item Create() {
...
return new Item(...);
}
}
and I have an Item class:
public class Item {
[AllowCallBy(typeof(Manager))]
public Item(...) {
}
...
}
Now, I would like to use the easiest and most straightforward way to analyze the attributes like AllowCallBy at compile time and display errors or warnings. If, in this particular case, a class other than Manager class tries to instantiate Item with new Item(...) I would like to display something like "don't instantiate Item class directly, call Manager.Create(...) instead".
I suppose that at least one of the systems: Roslyn, ReSharper, PostSharp or maybe something else would allow me to do it or something that is very close to what I'm trying to achieve. Could somebody give an example of what to use and how to use it?
This is definitely a code smell as #Habib mentions (can someone link to a specific one?), but without a more complete example it's difficult to offer alternatives beyond what has already been suggested in comments. I'd encourage you to expand your sample or rethink your design.
However, I can present one option that I've used in the past though not for this purpose. You could mark Item's constructor as Obsolete:
public class Item {
[Obsolete("Don't instantiate Item class directly, call Manager.Create(...) instead")]
public Item(...) {
}
...
}
Then in your Manager class, you'd specifically ignore this warning where you invoke the constructor:
public class Manager {
public Item Create() {
...
#pragma warning disable 618
return new Item(...);
#pragma warning restore 618
}
}
This way, whenever someone tries to create their own Item elsewhere in the code, they'll get a level 2 CS0618 warning indicating that they should not use the method (note that I didn't say cannot) with exactly the text entered in the attribute. If warnings as errors is enabled (for all warnings or just this one), then it will be a compile error as you originally wanted.
Be aware, nothing prevents others from adding these pragma statements to get around the error. However, with this method the developer can't say they didn't know they weren't supposed to use the constructor.
Well color me surprised. PostSharp lets you do exactly what you're looking for. In a nutshell, you'd use the ComponentInternalAttribute to control visibility of a type:
public class Item {
[ComponentInternal(typeof(Manager))]
public Item(...) {
}
...
}
According to their documentation linked above, attempting to invoke Item's constructor outside of Manager will yield a compile-time warning:
Method Item.ctor cannot be referenced from [some other method] because of the [ComponentInternal] constraint.
You can make it an error by changing the severity level of the attribute:
public class Item {
[ComponentInternal(typeof(Manager), Severity = SeverityType.Error)]
public Item(...) {
}
...
}
There are way better ways to achieve your goal than your current approach, given that you can actually change that code.
You could for example mark the contructor of Item class as private and add a static factory method to Item class which would be responsible for creating an instance of the class.
Another way is to move Item class to another assembly, mark its constructor as internal and implement another class (a factory) which would be responsible for creating different Item objects. Then you class is visible from other assemblies, but it cannot be directly instantiated, so forces the code user to use provided factory.

Resharper extract interface from object passed to method

I have a question if Resharper can help me with below problem.
Let's say there is a class with many properties inside:
public class TestClass {
public string variableA {get; set;}
public string variableB {get; set;}
public int variableC {get; set;}
}
then somewhere else we have a method that uses TestClass object
public void TestMethod(TestClass classInstance) {
classInstance.variableA = 'new value';
classInstance.variableC = 1;
}
of course this example is much simplified to the one I have, but I want somehow to extract interface that will have only
variableA
variableC
because then I want to pass it as a parameter to TestMethod. Can ReSharper do it automatically?
Right click the class
Select Refactor -> Extract -> Extract interface.
It takes you to extract interface window, in which you can select all the properties you want to extract it to a new interface.
In visual studio keyboard scheme shortcut happens to be ctrl + shift + R, x or select "Extract interface".
Once this refactoring is done, it is simply the matter of changing the method's formal parameter to use your interface as opposed to the concrete type.
I did what I wanted and I want to share solution, or maybe better say small workaround.
first what I did was to create an interface that contained all properties from the TestClass.
I changed method signature to get this interface instead of class itself.
I turned on wide analysis in R# and checked which properties are not used and removed them from the interface.
Maybe someone will need this in future when refactoring. Anyway - thanks for your help!

Inconsistent Accessibility error? [duplicate]

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.

Hiding unwanted properties in custom controls

Is this the way to hide properties in derived controls?
public class NewButton : Button
...
[Browsable ( false )]
public new ContentAlignment TextAlign { get; set; }
Also this hides the property in the Properties window in the designer but how can I also hide the property in code?
From code, the closest you can do it to hide it, and perhaps make it a pain to call directly - note that even when hidden it is callable, and none of this will work past a cast:
// about the closest you can do, but not really an answer
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("just cast me to avoid all this hiding...", true)]
public new ContentAlignment TextAlign { get; set; }
Personally, I wouldn't bother. It isn't robust (just cast).
You can use the [EditorBrowsable] attribute, as documented here.
[EditorBrowsable(EditorBrowsableState.Never)]
public bool HideMeInIntellisense
{
// ...
From the documentation:
...the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.
However, users can override this in VS settings. ReSharper also has a setting that controls whether this attribute is honoured in its IntelliSense.
Out of curiousity, why do you want to hide something from users? Just because a member is hidden in the way described above doesn't mean you couldn't use it in code and compile it successfully. It just inhibits the discoverability of the member.
No, you can remove them from the designer (as shown) but you cannot really hide them form code as that would violate the substitution principle. It has been asked & answered many times here, see for example this SO question.
Maybe what you want to do is derive from ContainerControl or UserControl, add a Button to that control and just expose those parts of the Button interface you want to keep.
Why don't you make it private? It guarantees that ancestors will not see it.
Edit:
In this case you have to inherit a new class from the base and use your new class, which now hides ths property.
public class MyTextBox: TextBox
{
...
private new ContentAlignment TextAlign
{
get { return base.ContentAlignment; }
set { base.ContentAlignment = value; }
}
}

Categories

Resources