Organizing using directives [duplicate] - c#

This question already has answers here:
Closed 14 years ago.
I've been using ReSharper for the past months and, advertising aside, I can't see myself coding without it. Since I love living on the bleeding "What the hell just went wrong" edge, I decided to try my luck w/ the latest ReSharper 4.5 nightly builds. It's all nice.
However, I've noticed that the using directives grouping format has changed, and I wanted to know which is closer to the general standards:
[OLD]
#region Using directives
using System.X;
using System.Y;
using System.Z;
using System.A;
#region
namespace X { ... }
[NEW]
namespace X {
#region Using directives
using System.X;
using System.Y;
using System.Z;
using System.A;
#region
...
}
Other than just lazy loading references, does it serve any special purpose? (Been reading Scott Hanselman's take on this # http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx)
Thanks;

As Scott proceeds to discover in his post, there is no runtime difference between these two cases. Therefore, it does not serve the purpose of lazy loading references.
If you read the comments in Scott's blog all the way to the end, you will also see that the developer who passed this rumor to Scott (Mike Brown) says that he had only heard of this and not tested it himself.
That said, it is possible that where you put the using directives might make a difference by giving a compiler error if you set up an alias for a type inside a namespace, and you have another type with the same name defined in the namespace. But that's no runtime difference of course.
Finally, I believe that MS coding guidelines say to do it as ReSharper 4.5 does. But it's silly to blindly follow this rule "because MS says so", since
It has been proved that it offers no benefit.
Your team's (or your) usual coding style may very well be different.

Well, the usual is subjective. :) But for me, the usual is the "old" way.

Oh, my bad. I didn't see that question when I searched for it. I know it's silly to do it 'cause MS says so, but in general, what's the "usual" approach to this?
I'm known to use ReSharper's code cleanup a lot, so I'm just wondering, to be honest.

Related

Compile Times: Additional Using Statements [duplicate]

I've always run Remove and Sort Usings as a matter of course, because it seems the right thing to do.
But just now I got to wondering: Why do we do this?
Certainly, there's always a benefit to clean & compact code.
And there must be some benefit if MS took the time to have it as a menu item in VS.
Can anyone answer: why do this?
What are the compile-time or run-time (or other) benefits from removing and/or sorting usings?
As #craig-w mentions, there's a very small compile time performance improvement.
The way that the compiler works, is when it encounters a type, it looks in the current namespace, and then starts searching each namespace with a using directive in the order presented until it finds the type it's looking for.
There's an excellent writeup on this in the book CLR Via C# by Jeffrey Richter (http://www.amazon.com/CLR-via-4th-Developer-Reference/dp/0735667454/ref=sr_1_1?ie=UTF8&qid=1417806042&sr=8-1&keywords=clr+via+c%23)
As to why MS provided the menu option, I would imagine that enough internal developers were asking for it for the same reasons that you mention: cleaner, more concise code.
There's probably a teeny-tiny (i.e. minuscule/virtually unmeasurable) performance improvement during compilation because it doesn't have to search through namespaces that you aren't actually using for unqualified types. I do it because it's just neater and easier to read in the end. Also, I use the Productivity Power Tools and have them set to do the Remove and Sort when I save the file.

What's the value in removing and/or sorting Usings?

I've always run Remove and Sort Usings as a matter of course, because it seems the right thing to do.
But just now I got to wondering: Why do we do this?
Certainly, there's always a benefit to clean & compact code.
And there must be some benefit if MS took the time to have it as a menu item in VS.
Can anyone answer: why do this?
What are the compile-time or run-time (or other) benefits from removing and/or sorting usings?
As #craig-w mentions, there's a very small compile time performance improvement.
The way that the compiler works, is when it encounters a type, it looks in the current namespace, and then starts searching each namespace with a using directive in the order presented until it finds the type it's looking for.
There's an excellent writeup on this in the book CLR Via C# by Jeffrey Richter (http://www.amazon.com/CLR-via-4th-Developer-Reference/dp/0735667454/ref=sr_1_1?ie=UTF8&qid=1417806042&sr=8-1&keywords=clr+via+c%23)
As to why MS provided the menu option, I would imagine that enough internal developers were asking for it for the same reasons that you mention: cleaner, more concise code.
There's probably a teeny-tiny (i.e. minuscule/virtually unmeasurable) performance improvement during compilation because it doesn't have to search through namespaces that you aren't actually using for unqualified types. I do it because it's just neater and easier to read in the end. Also, I use the Productivity Power Tools and have them set to do the Remove and Sort when I save the file.

Enhanced DynamicQuery?

I've recently started using the DynamicQuery API, and it quickly became apparent that it has numerous limitations. I've found at least one improvement online: support for enum arguments, but it's pretty clear that this API is not actively maintained (if at all).
In case I'm wrong and there is somebody maintaining an improved version - please post a link!
Alternatively, a separate, active project with similar goals would also be of interest.
(Clarification: I'm looking to parse strings at runtime.)
In the end we just implemented some of the features we missed by editing the source code. Added support for passing in a static class as an "external" (DynamicQuery's terminology), support for calling methods on this static class, and type inference if any such methods are generic.
I suspect there isn't much demand for this, so I didn't bother making it available anywhere. Let me know if you think otherwise.
Edit: due to a request, DynamicQuery Enhanced is now available on BitBucket. Expect to be underwhelmed; take a look at this Info and this list of tweaks.
I've seen PredicateBuilder before mentioned (here on Stackoverflow) as an alternative. I've not used it though, but it might be useful to you.

What should I know about C# before walking into an interview for a .NET job? [duplicate]

This question already has answers here:
Questions every good .NET developer should be able to answer? [closed]
(25 answers)
Closed 2 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!
Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.
Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.
EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.
They are likely going to ask you questions that are based more on Object Oriented Design and Programming more than questions that are explicitly geared towards C#. So if you can explain abstraction, polymorphism, interfaces, etc. You should be good to go.
Reference vs value types.
Know your delegates. Every .Net interview I've been on has asked me about delegates. Know why they exist, know how to declare them, and how to consume them, understand what multicast delegate is. Understand how to use a multicast delegate when one of the handlers throws an exception. Know what the compiler does with a delegate. Understand how delegates can give you "automatic" asynchronous APIs. Get familiar with the newer more convenient generic delegates - Action and Func.
Bonus: delegates vs events. What are the differences? When would you use one over the other?
Generics.
(also - don't try to cram and pass yourself off as an expert on something. A good interviewer will figure that out very, very quickly.)
I don't see how this question is valuable to your situation. The result of this question is going to be 30 posts listing features of the C# language.
I think you need to refine your question by giving us a hint about what type of job you are applying for. Or your skill set level or what areas your familiar with. Otherwise this post won't really contain a valuable answer.
EDIT
[OP] That (30 posts listing features of the C# language) is precisely what I am after
Then I suggest the C# language spec. http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx
ScottHa has two great lists of interview questions:
ASP.NET Interview Questions
What Great .NET Developers Ought To Know
Reflection. and the power of custom attributes in reflection.
Stack vs Heap: What goes where, what caused a StackOverflowException and what causes an OutOfMemoryException.
Generics, why generic lists are prefered rather then arraylist or hashtable. Performance issues and strongly typed added by the way.
Bonus: benefits of generic non-collection types. Why would one use these? How?
I hope the job interview is about coding itself. c# is just a syntax of programming. To be sure read about some specific C# things like reference vs value types
I'd start by looking at the latest c# enhancements. Also, it really depends on what type of job it is as there are a lot of things an ASP.Net developer won't know about Winforms and vice versa.
Assuming asp.net, I've been asked the following in interviews over the past 18 months:
Page Life Cycle
Generics
Interfaces / basic OO design
SQL; e.g. joins, updates, inserts,
etc. Also, how to use DataReader and
sqlcommand.
LINQ syntax; not because anyone is really using this, rather because they read about it.
Web Services ( asmx and wcf )
basic html / css
Session strategies for single server
/ load balanced
Differences between gridview,
repeater, etc.
What I've found is that most .net "web" dev's don't know diddly about sql or html. If you can prove you know more than just how to "drag and drop" controls on a web form then you're already better than 90% of the guys you'll run into.
If you've been writing code in one discipline (.NET in this case) that long, you should have a pretty standard answer to the technical questions that you don't know:
Q: So, what do you know about [technobabble]
A: Well, I haven't used that particular aspect in my previous projects, however, I have a small Volkswagen full of on-line resources that I check for answers like that. In other words, if I don't know it, I know where I can learn about it.
Optional addendum: "And here's an example of me dooing just that when I had a project that required [technobabble-2]..."
You know, if you just plummet through the ECMA-334 specification you should be all set. That's the language... but in away, you'll still be limited by your knowledge of the framework and that's experience. Hard earned experience.
OOPS Concepts
ADO.NET
Session mgmt and Caching
SQL Server distributed transactions
management
New features in .NET 2.0

Do you have any good advice/links to a set of coding standards or best practices to follow?

For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original author of the code you’re working on. Coding styles are often used for specific program languages and some styles in one coding language might not be considered appropriate for others. Of course some coding standards can be applied across many different program languages.
Thank you for your time.
EDIT: As we know there are many related articles on this subject, but C# Coding standard / Best practices in SO has some very useful links in there which is worth a visit. (Check out the 2 links on .NET/C# guidelines by ESV - Accepted Answer)
Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
My best advice regarding coding standards: don't let them get in the way when trying to get work done.
A big bureaucracy might actually hinder progress in projects instead of helping to achieve better team work. When people complain about not following coding standards instead of the actual quality of the code, then it is too much regulation.
Other than that, pick one from the many suggestions and try to stick with it for as long as possible to build a code base following a single standard that you are used to.
Coding standards are good, but coding standards written from scratch in which the company reinvents the wheel, or coding standards imposed by a single "prophet", can be worse than having no coding standards at all.
This means:
Coding standards should be discussed and agreed upon.
The coding standards document should include the reasons behind each rule.
Coding standards should be at least partially based on reliable sources.
The sources I know of for the languages in your tags are:
For C++: The book C++ Coding Standards by Sutter/Alexandrescu.
For C#: 4 or 5 PDF's I found googling for C# Coding Standards :)
Adam Cogan has a great set of rules on his web site. There are coding guidelines, but there is much more there also.
Adam Cogan's Rules to Better...
Coding standards are great. We've been using Lance Hunt's C# Coding Standards for .NET almost without modifications
If you are maintaining code that continue to use the same standard as the original code was developed in (there is nothing worse then trying to debug a problem when the code looks all higgildy piggeldy)
Some comment to the post suggesting looking at the Google C++ guidelines. Detailed discussion about some aspects of these guidelines are posted at comp.lang.c++.moderated.
Some weird or controversial points include:
We don't believe that the available
alternatives to exceptions, such as
error codes and assertions, introduce
a significant burden.
As if assertions were a viable alternative... Assertions are usually for programming errors and situations that should never happen, while exceptions can happen (are somewhat anticipated) in the execution flow.
Reference Arguments: All parameters
passed by reference must be labeled
const. ... In fact it is a very strong
convention that input arguments are
values or const references while
output arguments are pointers.
No comment, about weasel phrase a very strong convention.
Doing Work in Constructors: Do only
trivial initialization in a
constructor. If at all possible, use
an Init() method for non-trivial
initialization.  ... If your object
requires non-trivial initialization,
consider having an explicit Init()
method and/or adding a member flag
that indicates whether the object was
successfully initialized.
Yes... 2-phase init to make things simpler... What if I have const fields? This rule is probably the effect of attitude towards exceptions.
Use streams only for logging
Which streams? IOStreams, standard C streams, other?
On one hand they advise to use macros only in exceptional situations, while they recommend using DISALLOW_COPY_AND_ASSIGN to prohibit copy/assign. They could have advised the approach with special class (like in Boost)
Do not overload operators except in rare, special circumstances.
What about assignment, or arithmetic operators for numeric calculations, etc?
Default parameters are more difficult to maintain because copy-and-
paste from previous code may not reveal all the parameters. Copy-and-
pasting of code segments can cause major problems when the default
arguments are not appropriate for the new code.
The what? Copy/paste from previous code?
Remember that reading any of the guidelines can introduce a bias to your way of thinking. And sometimes it won't be beneficial for you or your code. I agree with some other posts advising reading good books by good authors beforehand. When you have sufficient amount of knowledge, then you are able to look at the guidelines and find good and weak points easily, without creating a mess in your brain ;)
If you plan to introduce a code-formatting standard to an existing programming team, get input from each member of the team so they'll have "buy in" and be more likely to write code to that standard.
Programming styles are as difficult to change as habits, and you'll have to accept that some people won't make their code 100% compliant 100% of the time. It would be worth your time to find (or write your own) pretty-printer program and periodically run all your code through it to enforce consistency. (I always felt uneasy when manually checking in source code changes that only consisted of formatting corrections for other peoples' code; I worried that others would label me a nitpicker.)
Sun Java Code Conventions
Python Style Guide
Zend Coding Standard for PHP
Having asked this question. I found that the accepted answer proved to be sufficient for my needs.
However, I realise that this is not a 'one-size-fits-all' scenario, so there is a large quantity of information within the thread that you may find more or less useful. Weel worth a read!
For Java and other C-family languages I recommend Sofware Monkey's coding standards (of course, since they're mine).
In general, keep them simple, and provide examples and justification for every requirement.
What's in the standard doesn't really matter all that much. What matters is that you have one, and that your developers follow it.
It doesn't quite answer the question, but it's worth a mention...
I read Steve McConnell's Code Complete. Whilst it doesn't give you a pre-baked set of coding standards it does set out a lot of good arguments for the various approaches. It'll make you think about things you'd not thought of before.
It changed my little world for the better.
Coding standards themselves are great and all, but what I think is much, much, MUCH more important is keeping with the style of whatever code you're maintaining. I've seen people add a function to some class written one way and forcing their coding standard on just that function. It's inconsistent, it sticks out, and, in my opinion, it makes it harder to enjoy the class "as a whole".
Whenever you're maintaining code, look at the code around it. See what the style is. K&R braces? Capital Camel Case methods? Hungarian? Double-line comment blocks between every function? Whatever it is, you should do it too in that specific area.
Before I leave, one thing I'd like to note that's related - naming files. I'm mainly a C++ guy, so this may not apply to whatever else, but basically it goes _.h or .cpp. So, Foo::Bar would be in Foo_Bar.h. Common things (i.e. a precompiled header) for the Foo namespace would be in Foo_common.h (note the lowercase common). Of course, that's a taste thing, but everybody who has worked with this has come out in favor of this.
i think Code Craft - The Practice of Writing Excellent Code pretty much sums it all up
Very popular are Ellemtel rules for C++.
For C# I recommend Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition) (Microsoft .NET Development Series).
Mono Coding Guidelines
The answers here a pretty complete, thus I am not pointing to another coding standard document. However, once you decided to stick to one style you should use an automated coding style enforcer throughout your team.
For Java there is checkstyle and for .NET Microsoft Style Cop.
Here is a similar discussion on Stackoverflow: C# Coding standard / Best practices
Camel and pascal casing alone solves a lot of coding standard problems

Categories

Resources