C# myths about best practices? - c#

My colleague keeps telling me of the things listed in comments.
I am confused.
Can somebody please demystify these things for me?
class Bar
{
private int _a;
public int A
{
get { return _a; }
set { _a = value; }
}
private Foo _objfoo;
public Foo OFoo
{
get { return _objfoo; }
set { _objfoo = value; }
}
public Bar(int a, Foo foo)
{
// this is a bad idea
A = a;
OFoo = foo;
}
// MYTHS
private void Method()
{
this.A //1 -
this._a //2 - use this when inside the class e.g. if(this._a == 2)
A //3 - use this outside the class e.g. barObj.A
_a //4 -
// Not using this.xxx creates threading issues.
}
}
class Foo
{
// implementation
}

The this. is redundant if there isn't a name collision. You only need it when you need a reference to the current object or if you have an argument with the same name as a field.
Threading issues have nothing to do with it. The confusion maybe comes from the fact that most static members are implemented so that they are thread-safe and static members cannot (!) be called with this. since they aren't bound to the instance.

"Not using this.xxx creates threading
issues"
is a complete myth. Just ask your co-worker to check the generate IL and have him explain why they are the same whether you add this or not.
"use this when inside the class e.g.
if(this._a == 2)"
is down to what you want to achieve. What your co-worker seems to be saying is always reference the private field, which does not seem to me sensible. Often you want to access the public property, even inside a class, since the getter may modify the value (for instance, a property of type List may return a new List instance when the list is null to avoid null reference exceptions when accessing the property).

My personal "best practice" is to always use this. Yes it's redundant but it's great way to identify from the first look where the state of the instance is chaged or retrieved when you consider multi-threaded app.

It may help to ask your co-worker why he considers these suggestions are best practice? Often people quote best-practice "rules" that they have picked up somewhere without any real understanding of the reasons behind the practices.
As Lucero says, the "this" is not required unless () there is a name collision. However, some people like to include the "this" when it is not strictly required, because they believe it enhances readability / more clearly shows the programmers intentions. In my opinion, this is a matter of personal preference rather than anything else.
As for the "bad idea" in your "Bar" method: Your co-worker may consider this bad practice for the following reason: if the setter method for "A" is altered to have some side effect then A=a; will also produce this side effect, whereas _a = a; will just set the private variable. In my view, best practice is a matter of being aware of the difference rather than prefering one over another.
Finally, the "threading issues" are nonsense - AFAIK "this" has nothing to do with threading.

The number 2 is a myth that is easily debunked by mentioning automatic properties. Automatic properties allow you to define a property without the backing field which is automatically generated by the compiler. So ask your co-worker what is his opinion about automatic properties.

Related

Is always prefixing (auto)properties with the this-keyword considered a good practice?

Ever since I found out about auto properties, I try to use them everywhere. Before there would always be a private member for every property I had that I would use inside the class. Now this is replaced by the auto property. I use the property inside my class in ways I normally would use a normal member field. The problem is that the property starts with a capitol, which makes it look a bit weird imho when using it in this manner. I didn't mind that properties start with a capitol before because they would always be behind a "dot". Now I have found myself prefixing all the properties I use internally with this., to sooth my feeling.
My dilemma is that before I was always a bit against prefixing all usage of internal members with this., unless "necessary" (like in a setter or constructor). So I am kind of looking for a second opinion on this. Is there a standard good way to do this? Should I just stop complaining (I have the tendency to be a "ant humper" (Dutch expression))?
Before:
class Foo
{
private Bar bar;
public Bar Bar { get { return bar; } }
public Foo(Bar bar)
{
this.bar = bar;
}
public void DoStuff()
{
if(bar != null)
{
bar.DoMethod();
}
}
}
After:
class Foo
{
public Bar Bar {get; private set;}
public Foo(Bar bar)
{
this.Bar = bar;
// or
Bar = bar;
}
public void DoStuff()
{
if(this.Bar != null)
{
this.Bar.DoMethod();
}
// or
if(Bar != null)
{
Bar.DoMethod();
}
}
}
Update
It seems that opinions vary, although more people are in favor of prefixing with this.. Before the auto properties I was always pretty much against prefixing with this. instead of in constructors and in setters (as I mentioned before). But now I just don't know anymore.
Additional note: The fact that it is also common to name the property the same as the class (public Bar Bar { get; private set; }) also makes me tend towards prefixing. Every time I type Bar.DoMethod(), I feel like it looks like a static method. Even though VS would color Bar if it was a static method and you cannot have a static and instance method with the same signature. When it is colored it is clear that it is a static method, but when it is not colored it is not 100% clear that it is not a static method. You could for example just be missing a using statement, but also just because I am not used to having to link the not being colored to whether it's a static call or not. Before I'd instantly see it by the capitalization of the first letter in case of a member or by the "dot" in case of a property (E.g. the "dot" after foo in (Foo)foo.Bar.DoMethod()).
(Difficult to choose an "Accepted answer" at the moment)
Yes, there is a "standard way to do this": the capital letter and the this-prefix are considered good coding practice. If you use some tool to test your code for coding guidelines like ReSharper or Microsoft's own StyleCop, it will warn you if not using the this-reference, or if you don't start your properties with a capital.
Your properties are publicly visible. Any public property, field or method should start with a capital.
Any property, field or method that you call inside your own class that is part of that class should be prefixed with the this-reference for ease-of-reading.
Update: of course, opinions vary. I like hitting this. and then, after the dot, seeing only the members, instead of seeing all keywords when just hitting ctrl-space without any prefix. This helps me. But, in the end (quote from here):
Whatever your opinion, the important
thing is that all people closely
collaborating on a project use the
same formatting standards,
irrespective of what those standards
are.
More references:
Microsoft on using a capital letter in almost any name and in properties specifically.
More guidelines here.
I strongly recommend to use 'this.' where possible. Framework Design Guidelines recommends this practice. It lets you know the scope from readability point of view and helps you avoid silly mistakes which compiler may report at compile time.
And I strongly recommend never using this as it only ever reduces clarity. If you actually find yourself in an instance where you need this to avoid collisions I would recommend renaming one of the fields/properties/variables.
The only place I find it acceptable is if it's part of a publicly exposed API where renaming would cause a breaking change.
In the first example, the bar parameter lexically shadows bar field from the instance. So you have to use this for disambiguation.
In the 2nd example you have no such ambiguity, and hence does not need a disambiguation (ie this). You can however still prefix it, if that is your cup of tea. :)

I know I'm doing validation wrong. Please persuade me to stop :)

First let me explain how I currently handle validation, say, for an IPv4 address:
public struct IPv4Address {
private string value;
private IPv4Address(string value) {
this.value = value;
}
private static IPv4Address CheckSyntax(string value) {
// If everything's fine...
return new IPv4Address(value);
// If something's wrong with the syntax...
throw new ApplicationException("message");
}
public static implicit operator IPv4Address(string value) {
return CheckSyntax(value);
}
public static implicit operator string(IPv4Address address) {
return address.value;
}
}
I have a bunch of structs like this one.
They often have additional private members to handle things but not methods are exposed publicly.
Here is a sample usage:
IPv4Address a;
IPv4Address b = "1.2.3.4";
a = b;
b = "5.6.7.8";
string address = a;
// c contains "1.2.3.4"
IPv4Address c = address;
// See if it's valid
try {
IPv4Address d = "111.222.333.444";
}
catch (ApplicationException e) {
// Handle the exception...
}
I can feel that there's something very disturbing with this, hence I'm pondering about switching to a static class with methods like IsIPv4Address and so on.
Now, here's what I think is wrong with the approach above:
New team members will have to wrap their heads around this
It might impede integration with 3rd party code
Exceptions are expensive
Never seen anything like this and I am a conservative type at heart :)
And then what I like about it:
Very close to having a lot of specialized primitives since you have value types.
In practice they can be often used like primitive types would, for example it isn't a problem passing the struct above to a method that accepts a string.
And, my favourite, you can pass these structs between objects and be sure that they contain a syntactically valid value. This also avoids having to always check for correctness, which can be expensive if done unnecessarily and even forgotten.
I can't find a fatal flaw to the approach above (just a beginner here), what do you think?
Edit: as you can infer from the first line this is only an example, I'm not asking for a way to validate an IP address.
First of all, you should read posts about implicit casting, and when to use it (and why it's bad to use it in your scenario), you can start here.
If you need to have checking methods, they should be public static, instead of such strange constructs, beside this, having such methods allows you to choose if you want to throw exceptions (like .Parse() methods do), or signal by returning some value that should be checked (like .TryParse() methods).
Beside this, having static methods for creating valid objects doesn't mean you can't use value type (struct) instead of a class, if you really want to. Also, remember that structs have implicit empty constructor, that you can't "hide", so even your construct can be used like this:
IPv4Address a = new IPv4Address();
which will give you invalid struct (value will be null).
I also very much like the concept of mimicking the primitive patterns in the framework, so I would follow that through and lean toward IpV4Address.Parse("1.2.3.4") (along with TryParse) rather than implicit cast.
Seems like a whole lot of complexity with no benefit. Just because you can doesn't mean you should.
Instead of a CheckSyntax(string value) that returns a IP (This method is poorly worded btw) I would just have something like a
bool IsIP(string)
Then you could put this in a utility class, or a base class, or a separate abstraction someplace.
From the MSDN topic on implicit conversions
The pre-defined implicit conversions
always succeed and never cause
exceptions to be thrown. Properly
designed user-defined implicit
conversions should exhibit these
characteristics as well
Microsoft itself has not always followed this recommendation. The following use of the implicit operator of System.Xml.Linq.XName throws an XmlException:
XName xname = ":";
Maybe the designers of System.Xml.Linq got away with it by not documenting the exception :-)

why C# does not provide internal helper for passing property as reference?

This is issue about LANGUAGE DESIGN.
Please do not answer to the question until you read entire post! Thank you.
With all helpers existing in C# (like lambdas, or automatic properties) it is very odd for me that I cannot pass property by a reference. Let's say I would like to do that:
foo(ref my_class.prop);
I get error so I write instead:
{
var tmp = my_class.prop;
foo(tmp);
my_class.prop = tmp;
}
And now it works. But please notice two things:
it is general template, I didn't put anywhere type, only "var", so it applies for all types and number of properties I have to pass
I have to do it over and over again, with no benefit -- it is mechanical work
The existing problem actually kills such useful functions as Swap. Swap is normally 3 lines long, but since it takes 2 references, calling it takes 5 lines. Of course it is nonsense and I simply write "swap" by hand each time I would like to call it. But this shows C# prevents reusable code, bad.
THE QUESTION
So -- what bad could happen if compiler automatically create temporary variables (as I do by hand), call the function, and assign the values back to properties? Is this any danger in it? I don't see it so I am curious what do you think why the design of this issue looks like it looks now.
Cheers,
EDIT As 280Z28 gave great examples for beating idea of automatically wrapping ref for properties I still think wrapping properties with temporary variables would be useful. Maybe something like this:
Swap(inout my_class.prop1,inout my_class.prop2);
Otherwise no real Swap for C# :-(
There are a lot of assumptions you can make about the meaning and behavior of a ref parameter. For example,
Case 1:
int x;
Interlocked.Increment(ref x);
If you could pass a property by ref to this method, the call would be the same but it would completely defeat the semantics of the method.
Case 2:
void WaitForCompletion(ref bool trigger)
{
while (!trigger)
Thread.Sleep(1000);
}
Summary: A by-ref parameter passes the address of a memory location to the function. An implementation creating a temporary variable in order to "pass a property by reference" would be semantically equivalent to passing by value, which is precisely the behavior that you're disallowing when you make the parameter a ref one.
Your proposal is called "copy in - copy out" reference semantics. Copy-in-copy-out semantics are subtly different from what we might call "ref to variable" semantics; different enough to be confusing and wrong in many situations. Others have already given you some examples; there are plenty more. For example:
void M() { F(ref this.p); }
void F(ref int x) { x = 123; B(); }
void B() { Console.WriteLine(this.p); }
If "this.p" is a property, with your proposal, this prints the old value of the property. If it is a field then it prints the new value.
Now imagine that you refactor a field to be a property. In the real language, that causes errors if you were passing a field by ref; the problem is brought to your attention. With your proposal, there is no error; instead, behaviour changes silently and subtly. That makes for bugs.
Consistency is important in C#, particularly in parts of the language that people find confusing, like reference semantics. I would want either references to always be copy-in-copy-out or never copy-in-copy-out. Doing it one way sometimes and another way other times seems like really bad design for C#, a language which values consistency over brevity.
Because a property is a method. It is a language construct responding to a pattern of encapsulating the setting and retrieval of a private field through a set of methods. It is functionally equivalent to this:
class Foo
{
private int _bar;
public int GetBar( ) { return _bar; }
public void SetBar( ) { _bar = value; }
}
With a ref argument, changes to the underlying variable will be observed by the method, this won't happen in your case. In other words, it is not exactly the same.
var t = obj.prop;
foo(ref t);
obj.prop = t;
Here, side effects of getter and setter are only visible once each, regardless of how many times the "by-ref" parameter got assigned to.
Imagine a dynamically computed property. Its value might change at any time. With this construct, foo is not kept up to date even though the code suggests this ("I'm passing the property to the method")
So -- what bad could happen if
compiler automatically create
temporary variables (as I do by hand),
call the function, and assign the
values back to properties? Is this any
danger in it?
The danger is that the compiler is doing something you don't know. Making the code confusing because properties are methods, not variables.
I'll provide just one simple example where it would cause confusion. Assume it was possible (as is in VB):
class Weird {
public int Prop { get; set; }
}
static void Test(ref int x) {
x = 42;
throw new Exception();
}
static void Main() {
int v = 10;
try {
Test(ref v);
} catch {}
Console.WriteLine(v); // prints 42
var c = new Weird();
c.Prop = 10;
try {
Test(ref c.Prop);
} catch {}
Console.WriteLine(c.Prop); // prints 10!!!
}
Nice. Isn't it?
Because, as Eric Lippert is fond of pointing out, every language feature must be understood, designed, specified, implemented, tested and documented. And it's obviously not a common scenario/pain point.

Why doesn't C# support local static variables like C does? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Why doesn't C# have local static variables like C? I miss that!!
Because they screwed up, and left out a useful feature to suit themselves.
All the arguments about how you should code, and what's smart, and you should reconsider your way of life, are pompous defensive excuses.
Sure, C# is pure, and whatchamacallit-oriented. That's why they auto-generate persistent locals for lambda functions. It's all so complicated. I feel so dumb.
Loop scope static is useful and important in many cases.
Short, real answer, is you have to move local statics into class scope and live with class namespace pollution in C#. Take your complaint to city hall.
The MSDN blog entry from 2004: Why doesn't C# support static method variables? deals with the exact question asked in the original post:
There are two reasons C# doesn't have this feature.
First, it is possible to get nearly the same effect by having a
class-level static, and adding method statics would require increased
complexity.
Second, method level statics are somewhat notorious for causing
problems when code is called repeatedly or from multiple threads, and
since the definitions are in the methods, it's harder to find the
definitions.
[author: Eric Gunnerson]
(Same blog entry in the Microsoft's own archive. The Archive.org preserved the comments. Microsoft's archive didn't.)
State is generally part of an object or part of a type, not part of a method. (The exception being captured variables, of course.)
If you want the equivalent of a local static variable, either create an instance variable or a static variable - and consider whether the method itself should actually be part of a different type with that state.
I'm not nearly as familiar with C as I am C#, but I believe you can accomplish everything you could with a local static, by using a class level static that is only used for one method. Obviously, this comes with some syntactic change, but I believe you can get whatever functionality you need.
Additionally, Eric Lippert answers questions like this on his blog a lot. Generally answered in this way: "I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature." Essentially his answers generally boil down to, it costs money to add any feature, and therefore, many potential features are not implemented because they have not come out on the positive side of the cost benefit analysis.
So you want to use a static local variable in your method? Congratulations! You made another step towards becoming a real programmer.
Don't listen to all the people telling you that static locals are not "clean", that they impede "readability" and could lead to subtle and hard-to-find "bugs". Nonsense! They just say that because they are wannabe programmers! Lots of them are probably even toying around with an esoteric functional programming language during their free-time. Can you believe it? What a bunch of hipsters!
Real programmers embrace a paradigm I like to call SDD - Side effect Driven Design. Here are some of it's most important laws:
Don't be predictable! Never return the same thing from a method twice - even if it's being called with the exact same arguments!
Screw purity - let's get dirty! State, by nature, craves changing, because it is an insatiable monoid in the category of polyamorous endofunctors, i.e. it likes to be touched by as many collaborators as possible. Never miss out on an opportunity to do it the favor!
Among the tools used to code in a side effect driven manner are, of course, static local variables. However, as you noticed, C# does not support them. Why? Because over the last two decades Microsoft has been infiltrated by so called Clean Coders that favor maintainability over flexibility and control. Can you even remember the last time you have seen our beloved blue screen? Now guess whose fault is that!
But fear not! Real developers don't have to suffer from those poor design decisions. As has been mentioned before it is possible to have local variables that are kind of static with the help of lambdas.
However, the provided solution wasn't quite satisfactory. Using the previous answer our almost-SDD-compliant code would look something like this:
var inc = Increment();
var zero = inc();
var one = inc();
or
var zero = Increment()();
But that's just silly. Even a wannabe developer can see that Increment() is not a normal method and will get suspicious. A real programmer, on the other hand, can make it even more SDD-like. He or she knows that we can make a property or field look like a method by giving it the type Func<T>! We just have to initialize it by executing a lambda that in turn initializes the counter and returns another lambda incrementing the captured counter!
Here it is in proper SDD code:
public Func<int> Increment = new Func<Func<int>>(() =>
{
var num = 0;
return () => num++;
}).Invoke();
(You think the above kinda looks like an IIFE? Yes, you are right and you should be ashamed of yourself.)
Now every time you call Increment() it will return something different:
var zero = Increment();
var one = Increment();
Of course you also can make it so that the counter survives the lifetime of your instance.
That'll show them wannabe programmers!
C# is a component-oriented language and doesn't have the concept of variables outside the scope of a class or local method. Variables within a method cannot be declared static either, as you may be accustomed to doing in C. However, you can always use a class static variable as a substitute.
As a general practice, there are usually ways to solve programming problems in C# without resorting to using method-level statics. State is generally something you should design into classes and types, not methods.
Logically, yes. It would be the same as a class-level static member that was only used in that one method. However, a method-level static member would be more encapsulated. If the data stored in a member is only meant to be used by a single method, it should only be accessible by that single method.
However, you CAN achieve almost exactly the same effect in C# by creating a nested class.
Because static local variables are tied to the method, and the method is shared amongst all instances.
I've had to correct myself and other programmers who expect it to be unique per class instance using the method.
However, if you make it a static class, or static instance of a class, it's syntactically clear whether there's an instance per container-class, or one instance at all.
If you don't use these, it becomes easier to refactor later as well.
I think the idea of local statics is just as easily solved by creating public static fields to the class. Very little logical change don't you think?
If you think it would be a big logical change, I'd be interested to hear how.
class MyClass
{
public static float MaxDepthInches = 3;
private void PickNose()
{
if (CurrentFingerDepth < MyClass.MaxDepthInches)
{
CurrentFingerDepth++;
}
}
}
You can use nested-class as a workaround for this. Since C# is limiting the scope of static variables to classes, you can use nested-class as a scope.
For example:
public class Foo {
public int Increment() {
return IncrementInternal.Increment();
}
private static class IncrementInternal {
private static int counter = 0;
public static int Increment() {
return counter++;
}
}
}
Here Foo supports Increment method, but its support it by the private nested class IncrementInternal which contains the static variable as a member. And of course, counter is not visible in the context (other methods) of Foo.
BTW, if you want to access to Foo context (other members and methods) inside IncrementInternal.Increment, you can pass this as a parameter to IncrementInternal.Increment when you call it from Foo.
To keep the scope as small as possible, my suggestion is to create a nested class per each such method. And because it is probably not so common, the number of nested classes will stay small enough to maintains it.
I think it is cleaner than anonymous functions or IIFE.
You can see a live demo here.
I don't see much added benefit to local statics, if you are keeping your classes single purpose and small, there is little problem with global static pollution as the naysayers like to complain about. But here is just one other alternative.
using System;
using System.Collections;
public class Program
{
delegate bool DoWork();
public static void Main()
{
DoWork work = Foo().GetEnumerator().MoveNext;
work();
work();
work();
}
public static IEnumerable Foo()
{
int static_x = 10;
/*
do some other static stuff....
*/
main:
//repetative housework
Console.WriteLine(static_x);
static_x++;
yield return true;
goto main;
}
}
If you can imagine some sort of Lippert/Farnsworth hybrid entity announcing GOOD NEWS EVERYONE!, C# 6.0 allows the using static statement. This effectively allows you to import static class methods (and, it seems, properties and members as well) into the global scope.
In short, you can do something like this:
using NUnit.Framework;
using static Fizz.Buzz;
class Program
{
[Test]
public void Main()
{
Method();
int z = Z;
object y = Y;
Y = new object();
}
}
namespace Fizz
{
class Buzz
{
public static void Method()
{
}
public static int Z;
public static object Y { get; set; }
}
}
While this is only available in C# 6.0, from what I understand the generated assemblies should be compatible with previous .NET platforms (correct me if I'm wrong).
You can simulate it using a delegate... Here is my sample code:
public Func<int> Increment()
{
int num = 0;
return new Func<int>(() =>
{
return num++;
});
}
You can call it like this:
Func<int> inc = Increment();
inc();

C# this.everything?

I've decided to use this.variableName when referring to string/int etc.. fields.
Would that include ArrayList, ListBox etc too?
Like:
private ListBox usersListBox;
private void PopulateListBox()
{
this.usersListBox.Items.Add(...);
}
...Or not?
And what about classes?
MyClass myClass;
private void PlayWithMyClass()
{
this.myClass = new MyClass();
this.myClass.Name = "Bob";
}
?
This looks kind of odd to me.
And I don't know if I should use this.PublicProperty or only private fields.
I'm not 100% with the C# terminology, but hopefully what I said makes sense.
I used to do that sort of thing, but now I find that IDEs are pretty smart about giving me a visual indication that I'm dealing with a member variable. I only use "this" when it's necessary to distinguish the member variable from a parameter of the same name.
the this. command will allow you to call anything that is in scope in the same class as you are executing. You can access private and public variables and since everything in c# is a object calling a class is the same as calling a string.
You don't have to use this in your code if you don't want to as it is implied in c# unless a method param and a global variable are the same.
Less is more. Less text to parse is more readable.
I use this in the constructors since my parameters and member variables have the same names (I don't like marking member variables with _).
public class A
{
int a;
public A(int a)
{
this.a = a;
}
}
If your class is small enough and does one thing well, then usually you wouldn't need to add this for the sake of readability.
If you can read the whole class easily, what would be the point? It'd be more typing and clutter the code, thus possibly degrade the readability
using the 'this' keyword can be against any instance of an object. So this means u can use it to reference a class instance (eg. usersListBox, myClass, etc).
It's perfectly fine.
Some people use it to clearly explain what they are referencing so people understand that the instances are in the scope of the code and not external or part of another instance or static member elsewhere.
Finally, you can use it to reference both private and/or public properties and fields and members.
This is nothing more then a keyword pointing to the current instance. In a function, this.foo is generally the same as foo.
As msdn tells you:
The this keyword refers to the current instance of the class.
The page about the this keyword contains a lot more info.
As the this. is implicit you only need to actually use it when disambiguating between class variables and local variables of the same name.
The examples you've given would work how you've written then or like this:
private ListBox usersListBox;
private void PopulateListBox()
{
usersListBox.Items.Add(...);
}
MyClass myClass;
private void PlayWithMyClass()
{
myClass = new MyClass();
myClass.Name = "Bob";
}
it's just a matter of personal preference. If you do choose one over the other, try to be consistent.

Categories