C#: Un-nested struct in same .cs file as related class? - c#

If I'm dealing with one class and one public struct (not nested), Should I create a separate .cs just for the struct? Or leave it un-nested in its .cs file of the class? (This is assuming the struct relates to the class, but isn't so exclusive to the class that it should be nested and declared private)
Edit: I removed my initial question about two classes because I found C# classes in separate files?

Note that the only person(s) that can accurately answer this question is you, and your team. If your team is happy to find several related types inside a single file, combined due to ... whatever... then what I, or whomever other person, says, should be just ... irrelevant.
In any case, I would turn the question upside down:
Is there any reason to place two separate types (related by names, functionality, or whatever, but separate nonetheless) in the same file
and I've yet to come up with a good reason.
There are extensions/addins to Visual Studio where you can type in the name, and quickly navigate to the file, and I can think of three, but there are undoubtedly others:
DPack
ReSharper
CodeRush/Refactor! Pro
The first allows you to quickly navigate to a file by name. If you know the type, but have people putting multiple types into the same type, this will not be helpful, at all.
The second and third, lets you navigate to a type by name, but you shouldn't rely on people having those, or knowing how to use them.
To that end, I would advocate following these rules:
Project names should be identical to the root namespace of that project. I differ from this point myself where in some cases I name my projects "...Core", and I then remove "Core" from the namespace, but otherwise, leave the project name identical to the namespace
Use folders in the project to build namespace hierarchies
The name of a type should correspond 100% to the name of the file + whatever extension is right for your language. So "YourType" should be "YourType.cs", "YourType.vb" or "YourType.whatever" depending on language

That depends on who you ask.
I, personally, find it easier to read if they are all, always, broken out. However, the compiler doesn't care... so whatever you and your team agree is easier to understand.

In my opinion it's a good practice to avoid that. Some day a developer will be looking around for ClassBar in the project and won't be able to find it easily because it's nested in ClassFoo.cs
Tools like Resharper have a neat feature where you can just select a class, right click, place in new file to make this easier.
If you read any of the popular coding standards (Lance Hunt, iDesign, Framework Design Guidelines etc) most of them advocate 1 class per file.

Its annoying to scroll down and search for how many class each.cs file contains/hides.
Maintainability issue while using version control
Usability with our team.
Check here for more interesting discussion on same.

I think it was less about whether you can or whether you should. For things like this, I feel it's best to look to the convention in the rest of the codebase. Sometime conformity is better because it makes other developers jobs easier becaues everybody knows where things are.
If it's entirely new project and you are setting the standards here by yourself, do what makes sense to you. To me if the struct has no use outside the related class, I may put them in the same file. Otherwise, I seperate them out.

Related

Type name does not correspond to file name?

This warning message is popped up when my mouse is over my class name, I can understand that the file name should be named exactly as the class name (or vice-versa) (which is defined in the cs file). That will be OK and of course good to follow but what if I intend to define more 1 class in a cs file? Or I shouldn't do like that?
I don't like any warning message, it seems to mean that I'm doing thing abnormally and in a non-standard way.
As comments point out it is not comment put by C# compiler (or Visual Studio).
There is no restrictions in C# on number of classes per file or if class/namespace should match file/folder name (unlike Java or ActionScript).
It is considered good practice to have one class per file (not counting nested classes) and somewhat match folder names to namespaces. This makes code easier to search and easier to find files corresponding to particular classes.
As for length of classes again there is no technical restriction, but long classes generally mean too many responsibilities in one class and as result not recommended. Generally there is no reason not to have many small classes in individual files.
You need to come up with style that works for you/people you work with and try to stay with it. Most code analysis/style checking tools (like ReSharper) are very flexible in style checking, so you often can adjust rules to your liking.
The first class in the file should be named same as the filename. If you need other classes that are only used by this class you can put them below this top level class and you will not get any warnings.

How to organise class files in C#

I am working on a simple project and I have created several classes, interfaces, one static class and so on. What I am asking is, how to organise this files into namespaces. Is there any good practice for this or I should just follow the logic of my program. I am currently thinking that I should move the interfaces into one namespace and all the classes into another. So what can you advise me. I am really curious to find out the best way to separate my files.
Have a nice day :)
You should group your code in namespace with other types which have the highest cohesion. That is, group types together when they perform common functionality. The type of cohesion you're suggesting is logical cohesion, and is really a rather weak form of cohesion.
Namespaces are mainly for the benifit of large projects. Since you are working on a "simple project", I suggest that you use a single namespace for the entire application. Since everything in C# must be a type or a member of a type (i.e., there are no global variables or methods), the types that you create (objects, classes, interfaces, enums, etc.) are usually a good-enough organizing feature for a small project.
For slightly larger projects, I suggest putting each tier into its own namespace.
For even larger projects, namespaces should be a logical grouping of related types or subsystems, according to preference.
Into specific namespace you should put everything which concerns some matter. For example all the stuff concerning string manipulations you should put into separate namespace, e.g. com.server.string.
It's very important especially in case you have class with names existing in other namespaces.
The only reason to split your code in files is to make your code maintainable.
As a general rule of thumb, I tend to create folders for enum's, struct's, models, controllers, etc. Depending on the size of the solution, you keep nesting in groups after that.
Sometimes it makes sense to just put the entire namespace in the file, other times, you let your nesting take care of the naming.
A good rule of tumb is that you should be able to find what you are looking for quicky, and, more importantly, someone who hasn't seen the project, should find his way around quickly.
One thing to keep in mind is that you never put more then one thing in one file. Never put two classes in the same file, never append enums at the end of a class file, etc.
You are confusing files with classes. You can create folders in Visual Studio to organize your files. That way you can group interfaces and classes (which is what I usually do). VS will automatically put new classes for which the file is in those folders in the namespace of the same name. This is usually not what you want (I don't know how to turn it off, so I can't help you with that).
I agree with the other answers here that you should group types based on what they do, not on what kind of language construct they are.

Is this the good pratice to name the namespace according to the directory name

I have a directory structure to store the source files. Is this the good practice to
name the naming space according to the directory structure?
Like
Models\model.cs
Data\data.cs
One is defined in namespace Models
One is defined in namespace Data
Yes, that's the typical approach, and it's also one that's supported by tools such as ReSharper.
The difference between this and the Java approach is that you don't add directories all the way down from the top - just from the default namespace for the project. So for example, suppose we were creating Foo.Bar.Baz.Model and Foo.Bar.Baz.Data, the C# and java solutions might be:
C#:
Foo.Bar.Baz
Foo.Bar.Baz.csproj defining a project with default namespace of Foo.Bar.Baz
Model\
SomeModel.cs
Data\
SomeData.cs
Java:
src\
foo\
bar\
baz\
model\
SomeModel.java
data\
SomeData.java
yes is the usual practice, but you also put the project name before the directory name so you will have: myclasslibraryname.Models.Model and myclasslibraryname.Data.Data
Yes. It is a common practice in Java (at least, the source code I've looked at for big projects has almost always been structured this way). Not as common in C# from what I've seen, but there's nothing keeping you from doing it, and it helps you find the code a lot faster.
You'll probably want a deeper namespace hierarchy than just one level though. It is common to preface it with your organization or group name, the project name, the library/program name, then code architectural names (like Model, View, Data, etc). Whatever makes the most sense for whatever scope the source code of your project will live.
Generally I think it is a good practice. When you do it in such a manner, while going through the code, you can generally associate or easy to locate and get to know where your code file is coming from.
This is also a good practice in terms for maintaining the code. Some new user comes in, he can just see the namespace and identify where the code files are located or needs to be searched.
I don't know really if this is good or not.
But I name it like this.
I defined categories for the different modules.
Like this:
Company.Common
Company.Common.Web
Company.Windows
Company.Windows.Services
Common represent a directory. Inside it I created a solution with VS2010.
Inside the solution I create a project for each part and therefor the subdirectories for the project and if the project is complex, more sub dirs for the existing classes inside the dll.
There I have a good overview in all views (dir - view and project view - code view ).
This is a convenient convention for many projects, and one which some tools support or expect.
However, this isn't the full story. Although it's a good default, I don't think it should be regarded as inviolable best practice, because there are some circumstances which might motivate doing things another way. Additional factors to think about include:
Unnecessary namespace proliferation
and deeply nested namespace
hierarchies can be a pain for users
of your types. In a large library you
may want to start organising the
source code files into some folder
structure before you feel the need to
impose multiple namespaces on your
clients.
Related to this, namespace
hierarchies in .NET are supposed to
work such that dependencies between
types go from child namespace to
parent, not the other way around.
This isn't always the natural way to
organise source code into
folders/directories. For example, one
often sees people creating namespaces
such as MyNamespace.Foo.Common
containing utility types used both by
types in MyNamespace.Foo.Bar1 and
those in MyNamespace.Foo.Bar2. It
seems sensible to them at the source
code organisation level, but it
breaks the namespace dependency
convention.
Sometimes you may want to provide
additional functionality by adding
some types to a library namespace by
distributing a supplementary assembly
rather than releasing a completely
new version of the full library
assembly. It's likely to be more
convenient to keep source code files
for the respective assemblies
separate from each other in the
repository, rather than to store them
together just so as to keep all types
for the namespace in the same folder.
In short, I'd say follow the usual practice unless you have a good reason to do otherwise. But don't let it deter you, if you have a good reason to make use of the fact that Namespaces can provide a grouping of types completely orthogonal to their grouping into deployable assemblies and the source code which builds those.

Is it good practise to have multiple class definitions in one file?

Is it good practise to have multiple class definitions in one file? or is it preferable to have one class per file?
I prefer one class per file. You'll never have to search for the correct filename because it is always the class name.
One class per file.
That way you can avoid having to merge edits when two people have to edit the same file because one is working on class A and the other is working on class B. While this should be automatic in any source control system, it's an extra step that can be missed which would cause problems.
Far better to have a process that didn't allow this sort of error to occur in the first place.
I do not see any issue with multiple classes in the same file, as long as the classes are related to each other.
If you have resharper, you can always use the navigation tools to find any class.
It is generally best practice to have one file per class.
Some folk, not me, like to have more than more one if they are related and very very small in size. Others might do this in a prototyping stage. I say start and stay with one per file as does Scott McConnell in his discourse on Class Quality in his seminal book Code Complete
To quote, "Put one class in one file. A file isn't just a bucket that holds some code. If your language allows it, a file should hold a collection of routines that supports one and only one purpose. A file reinforces the idea that a collection of routines are in the same class."
I think it's preferable to have one class per file and to organize them in folders having the same hierarchy as their namespaces.
Most programmers would consider one class per file to be a best practice.
Usually - no.
Following practice "one class per file" simplifies browsing of solution.
Additionally if you have a big team of developers and source control tool that uses pessimistic approach (exclusive locks) - your developers will have hard time while working on the same file.
I guess it is down to preference as you said.
I think you'll find most online examples/ most code is one class per file for easy management.
I sometimes put 2 classes in a file - only if i'm using the second class as an entity and it's only being used in the first class.
I guess you ask because you've noticed already that it's considered best practice. Given the obvious benefits (and some less obvious ones mentioned here), why would you want to do it differently? Are there any benefits at all in multiple classes per file? I can't think of any.
Usually it is the best solution to have one class per file (with the file named exactly like the contained class).
I only differ from that if
There are lots of small enumerations ->I collect these into a single file e.g. Enums.cs
There are lots (20+) of generated classes/interfaces that directly relate to each other ->Into one file E.g. Interfaces.cs
There is stuff that is no direct functional part of the application and in close semantic consistance (e.g. everything you need for interop. Thats usually a few structures, enums, constants and a single class) -> That goes into a single file named after the interop class.
Private inner classes -> Stay with their parent class instead of partial classes
I would say no, i know devexpress hates it aswell ( It has some detection bad practives).
But i do have it sometimes, when its a very small class thats basicly only used by the "main" class in the file. Personaly i think it comes down a bit to taste, there is a balance between having 10k lines long .cs files or having to many .cs in your project.
I think in terms of it being a "best practise" approach then probably yes. However, really it depends on the project. I tend to group related code into separate units for example:
MyApplication.Interfaces
MyApplication.Utils
MyApplication.Controllers
I really think a class only ever deserves it's own unit if it becomes huge. However, if it does get to this stage, you should start to consider moving some code into helper classes to separate the logic.
I would have to agree with most on this. One class per file is ideal. It makes it easier to see what's available in a project without having to rely on intellisense to discover types that are available in a given assembly.
I think the only time I ever fudge on the one class per file rule is when I'm defining a custom EventArgs class and it's related to an event that's fired from another class. Then typically I would define those in along with a delegate for the event in the same file. I don't know that it's a good practice one way or another or just out of sheer lazyness??
If you work on a very large project, too many files can slow down your build times significantly (at least with C++). I don't think that rigid adherence to a rule is necessarily the way to go.
One Class Per File is my Preferred approach, it helps me get rid of any confusion later on... I tend to use a lot of partial classes though...
As long as I dont break the 1000 line barrier, I'll stuff in as many related classes that makes sense.
Sometimes an abstraction may only be one overridden method.

Naming types in a namespace by the .NET Framework Design Guidelines

I'm having some problems to come up with a sane type naming scheme for our new line of applications. I want to follow the .NET Framework Developer's Guide - Design Guidelines for Developing Class Libraries, but I'm starting to wonder if that's such a good idea.
I'd like to use the Company.Product.Feature namespace scheme as a basis.
Problem 1: We have our own control and form base classes, and I want these to go into the Company.Product.Forms namespace. However, according to the guidelines, we shouldn't let our type names be Control or Form, even if they are in our own Company.Product.Forms namespace, since they will clash with system types.
Problem 2: We have some distinct feature areas in the application and I want these to go into their own Company.Product.Feature namespace. Lots of these features have similar design, with a controller and some views, so under each Company.Product.Feature namespace I'd like to have types named Controller, SomeView, AnotherView, etc. However, according to the guidelines, we shouldn't have the same type names in different namespaces.
The only solution I see to overcome these problems is to prefix the types with something that in some way makes the namespaces redundant. Or not?
Microsoft clearly favors some redundancy. A common example is:
System.Xml.XmlDocument
General class names, even bound within a proper named namespace can cause headaches for the many programmers who like to avoid fully qualifying their class instantiations. "Document" could be an Xml, Html or word document. This ambiguity will cause endless confusion if you happen to import more than one namespace with a "Document" class.
I'd prefer Company.Product.UI, for some reason. I would use that naming for the web, too.
Regarding problem 1, if these are base types, you might include Base in the class name.
Then, you typically have a set of domain specific controls, which won't clash with built-in types.
If you also keep wrappers for common UI controls(TextBox, DropDownList etc), then i would actually recommend use a prefix for them,
maybe this prefix is an abbreviated name of the product.
And then, if you do that, then you might want to be consistent, and do it for all types,
regardless of whether they are ambigious names or not.
I tell you from my own experience.
You'll end up constantly hovering over variables to see their full type names, etc, you will use aliasing etc..
The code will be harder to read.
Problem 2: While at GUI layer, i tend to break these rules, because you will want naming consistency(common verbs; Show,Edit,List). If the guideline tells you otherwise, i would believe it is because it is simply not specific enough.
First post here in StackOverFlow, on an old question. Please, be kind with me :)
General class names, even bound within a proper named namespace can cause headaches for the many programmers who like to avoid fully qualifying their class instantiations. "Document" could be an Xml, Html or word document. This ambiguity will cause endless confusion if you happen to import more than one namespace with a "Document" class.
Microsoft MIGHT sometimes favor some redundency but it's not always de case.
As for the Document vs XMLDocument problematic, when you know there might be more than one type of document, why not just include the qualifying part of the namespace in the declaration?
For example :
Xml.XmlDocument
vs
Html.HtmlDocument
Instead of importing the XML and HTML namespace, why not just include the containing namespace? It would become like this :
Xml.Document
vs
Html.Document
If it makes logical sense, then do it. They are just guidelines, not the LAW. (not that you cant break that too.)
Having classes in the with the same name in different namespaces is just is against the guidelines for a reason, it makes reading the code just a little bit harder because when you see "Controller" you have to mentally map it to "Feature1.Controller" or "Feature2.Controller".
I would prefer to use Company.Product.Features.Feature1.Feature1Conroller with the redundant information or maybe Company.Product.Features.Feature1Controller if it bothers you (and I personally don't like having too many namespaces).
But feel free to break the guidelines, rules are there to make you think before you break them :-)

Categories