rspec/rules/S2292/csharp/rule.adoc

94 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Trivial properties, which include no logic but setting and getting a backing field should be converted to auto-implemented properties, yielding cleaner and more readable code.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
public class Car
{
private string _make;
public string Make // Noncompliant
{
get { return _make; }
set { _make = value; }
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
public class Car
{
public string Make { get; set; }
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make this an auto-implemented property and remove its backing field.
'''
== Comments And Links
(visible only on this page)
=== on 16 Dec 2014, 20:40:12 Ann Campbell wrote:
\[~dinesh.bolkensteyn] what about a property which has logic in one of the methods but not the other?
=== on 17 Dec 2014, 06:38:06 Dinesh Bolkensteyn wrote:
I've tested that yesterday [~ann.campbell.2], it's not possible: There is no way to explicitly access the implicit backing field, so there is no way to add any logic to an auto-property.
=== on 17 Dec 2014, 13:01:10 Ann Campbell wrote:
\[~dinesh.bolkensteyn] I'm not sure I was clear. I'm talking about something like this:
----
private string _make;
public string Make // Noncompliant
{
get { return _make; }
set
{
// do stuff to value...
_make = value;
}
}
----
=== on 17 Dec 2014, 13:05:37 Dinesh Bolkensteyn wrote:
So you actually mean:
----
private string _make;
public string Make
{
get { return _make; }
set
{
if (value == null)
{
throw new SomeException();
}
_make = value;
}
}
----
That is perfectly valid and compliant. There is nothing that can be improved there.
endif::env-github,rspecator-view[]