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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to be able to distinguish between a generic and regular (non-generic) version of a class. Much like the .NET framework does with it's generic and non-generic versions of several of it's interfaces and collection classes. (Queue, Queue(T))
I generally like to follow the convention of one class per file (as in Java). Is there a common convention for naming files containing a single generic class? I'm mostly interested in Windows (NTFS specifically) but it seems like a good convention would be (at least a little) portable.
At Microsoft, they use ClassNameOfT.cs.
Just found this question after looking for what conventions other people use for generic class filenames.
Lately I've been using ClassName[T].cs. I really like this convention, and I think it's superior to the others for the following reasons:
The type parameters jump out at you a
little more than they do with the
Microsoft convention (e.g.,
ClassNameOfT.cs).
It allows you to have multiple
type parameters without too much
confusion: Dictionary[TKey,
TValue].cs
It doesn't require you to create any special folders, or to have your generic classes in a special namespace. If you only have a few generic classes, having a special namespace dedicated to them just isn't practical.
I borrowed this convention from Boo's generic syntax, albeit slightly modified (Boo uses ClassName[of T]).
Some developers seem to have a phobia of filenames that contain anything but letters and underscores, but once you can get past that this convention seems to work extremely well.
I see that this topic has been abandoned more than a year ago, but still I would like to share my view on this convention.
First of all, having multiple classes that have the same name but only differ in the amount of type-parameters isn't always a case of backwards compatibility. Surely, you don't see it very often, but the new Action- and Func-classes of .NET were just designed this way, and I'm currently implementing something similar.
For clarity and distinguishability, I use the following convention that only specifies the number of generic arguments for a given type:
MyClass.cs
MyClass.T1.cs
MyClass.T2.cs
This way, my filenames stay short and simple while still clearly communicating the class-name and the different amount of type parameters at the cost of a simple extra dot (which is, in my experience, a commonly accepted thing to do in a filename and looks much better than comma's and other non-alpanumeric characters, but this is just a matter of taste I guess). Putting the names (or acronyms) of the type parameters just lengthens the filenames while at this level I'm not really interested in the actual names of the type parameters anyway...
Don't use the grave accent ` in your generic file names if you're running Visual Studio 2008. There's a known issue with them that causes breakpoints to fail:
http://connect.microsoft.com/VisualStudio/feedback/details/343042/grave-accent-in-filename-causes-failure-to-recognize-target-language-breakpoints-fail
Personally I wouldn't use the grave accent notation:
Foo.cs
Foo`1.cs
For the simple reason that I am scared of the grave accent. Not only does it have a scary name 👻😨😱, but I am unsure how it will be handled by different file systems, version control systems and in URLs. Hence, I would prefer to stick to common alphanumeric characters.
NameOfT.cs seems to be used in ASP.NET Core according to a search on GitHub. 40 results. Reference.
Also used in the .NET Core runtime. 36 results. Reference.
Example:
Foo.cs
FooOfT.cs
Sometimes I also see ClassName{T}.cs but it is common to name it ClassNameOfT.cs (like mentioned before Microsoft uses it)
EntityFrameworkCore project(also Microsoft's) uses ClassName`.cs
All new Microsoft classes use generics. The Queue and ArrayList were there before generics came out. Generics is the way forward.
The convention for one-class-per-single file is to name the filename after the class name (whether generic of not). For MyClass, you'll have MyClas.cs. For every new namespace you'll need to create a new folder. This is how Visual Studio also works.
How about:
Type.cs
and
TypeGeneric.cs
Whenever I have done this in the past I have always put both types in one file with the non-generic type as the file name. I think that this makes things pretty clear as .NET has no conventions/restrictions on one type per file like Java does.
But if you must then I would suggest something like I have above, and using a suffix will make the files show up together in any alphabetized list (Solution Explorer, Windows Explorer, etc.).
Here is another idea:
Type`1.cs
This would allow you to break out different generic types by the number of generic type parameters they accepted. Its just a thought though as I still think it would be simpler to just put all the types in one file.
I would probably put them in folders and use the namespace mechanism instead. You can compare with System.Collections vs. System.Collections.Generic. On the other hand, if it's more common than not that the classes use generics, perhaps it's better to point out those that are not. That is if you really want to separate the generic classes from other classes. Personally I usually don't bother to do that, since I don't really see a practical benefit from it.
From the responses so far it seems there isn't a consensus.
Using the same filename in a sub-namespace (and sub-folder) "Generics" (like System.Collecctions.Generics) is an option. But it's not always desirable to create a new namespace.
For example, in an existing namespace with non-generic classes that are maintained for backwards compatibility, but marked with ObsoleteAttribute, it's probably better to keep the generic versions in the same namespace.
I think a suffix is a reasonable way to go. I've adopted a convention of using the type parameters as a suffix (so: MyClassT for MyClass<T>, or MyDictionaryKV for MyDictionary<K,V>.
I'd probably have two folders in the project, something like Gereric, NonGeneric or something like that. They can still be in the same namespace, and then they can both have the same file name. Just a thought...
Related
I have a C# assembly that uses "$(FrameworkSDKDir)\Bin\NETFX 4.0 Tools\tlbexp.exe" "$(OutDir)My.dll" /out:"$(TLBDir)My.tlb" so that I can call it from native components
I am looking at
.tlh generated on 2 machines is different and it appears to be a similar problem, but my difference is in visual2010 the tlh is generated using one case, and in 2012, it is generated using a different case.
Even more interesting this just happened a day ago. I have a build from the 18th that worked just fine, and the code has not changed in either solutions for many days.
Any thoughts before i continue down the /Names option?
I cannot easily tell you what to do to solve this problem, just highlight why this is happening. It doesn't have much to do with Tlbexp.exe, it is generic behavior implemented in the type library support built into Windows.
It has a tricky problem to solve, it cannot make any assumptions about the kind of language that was used to generate the types. The troublemakers are languages that are case-insensitive, Visual Basic being the prime example. Also the original language for which type libraries were invented. The issue is that it may emit names that can have different casing in different declarations but identify the same type. If the type library would use the same casing then it could only ever be consumed by a language-insensitive compiler.
So it does something about it, the algorithm it uses can at best be described as crude however. It looks at any name, regardless of what part of a declaration it is used, then forces the casing of any subsequent same name it encounters to the same casing. The usual big surprises are caused by names of function arguments. They can change the name of a function if it happens to match. So an "item" argument, pretty common, can spoil the name of an "Item" property. Or the other way around.
The wild-card here is order, I suppose that could be half an explanation.
Best way to address the problem is to change the name so there is no longer a collision. You have no trouble finding them, it is the one that changed casing. You may have to iterate a few times to find them all. Given that it is usually the name of an argument that causes this, feel free to change the argument name. Just put an underscore after it for example, it doesn't break binary compatibility nor the client code.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why C# is not allowing non-member functions like C++
Instead of writing StaticClass.Function() I'd like to simply write Function(). There will be many functions and all should be accessible from different (and unrelated) classes and files. How do I put these functions in a specific namespace? Simply declaring it there will give me a compile error
error CS1518: Expected class, delegate, enum, interface, or struct
I know other .NET languages can do it. Is there a compile option i may use? Perhaps even undocumented?
C# does not allow for free functons. Each function must reside in a type. This is just the way it works, it's not a matter of technical possibility, it was a design decision.
You may be interested in this article.
On a side note, ever notice how Intellisense works much, much better when writing C# than C++? This is one of those things that help (not the only one, but one).
EDIT: Funny, in reading that linked article I noticed that this is a dup...
C# does not allow this, by design.
However, if your goal is merely to reduce typing, you have a couple of options.
First, you can use the using Directive to simplify this. By adding this:
using SC = YourNamespace.StaticClass;
You can shorten the calls within that specific document to:
SC.Function();
Another option which is occasionally appropriate would be to use an
Extension method. This can eliminate the need to specify the type, as the function appears to be a member function of the first argument. Of course, this wouldn't work for the supplied example (as it requires a parameter), but is potentially another option to reduce the amount of typing and searching, depending on the specific use case.
C# is a purely object-oriented which means you cannot have functions or declarations outside of a class. You'll have to use static to achieve what you want.
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
I'm working on an MVVM project, so I have folders in my project like Models, ViewModels, Windows, etc. Whenever I create a new class, Visual Studio automatically adds the folder name to the namespace designation instead of just keeping the project-level namespace. So, adding a new class to the ViewModels folder would result in the namespace, MyProject.ViewModels instead of just MyProject.
When I first encountered this, it annoyed me. My class names are pretty clear, sometimes even containing the name of the folder in them (e.g., ContactViewModel). I quickly found myself manually removing the folder name on the namespaces. I even tried at one point to create a custom class template (see this question), but I couldn't get that to work, so continued doing it manually.
I've begun to wonder, though, if this convention exists for a good reason that I'm just not seeing. I could see it being useful if you for some reason had lots of sets of identical class names organized into folders, but that doesn't seem like a particularly common scenario.
Questions:
Why is it common convention for namespace names to reflect folder structure?
Do you abide by this convention? Why?
Same as you - I fought this for the longest time. Then I started considering why I created folders. I found myself starting to create folders to represent namespaces and packages instead of arbitrary buckets.
For instance, in an MVVM project, it might be helpful to put views and view models in a separate namespace. MVC will have a separate namespace for Models, Controllers, and Views. It is also beneficial to group classes by their feature.
Suddenly, the project feels more organized. It is easier for other developers to find where features are implemented.
If you standardize on your namespace practices, all of your projects will have the same predictable structure which will be a big win for maintenance.
If you want some solid advice I'd recommend buying Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries which gives you all you need to know from the actual framework design team.
...the goal when naming namespaces is creating sufficient clarity for the programmer using the framework to immediately know what the content of the namespace is likely to be...
<Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]
And importantly
Do not use the same name for a namespace and a type in that namespace
Fragmenting every 1/2 types into namespaces would not meet the first requirement as you would have a swamp of namespaces that would have to be qualified or used, if you followed the Visual Studio way. For example
Core
- Domain
- Users
- Permissions
- Accounts
Would you create
MyCompany.Core.Domain.Users
MyCompany.Core.Domain.Permissions
MyCompany.Core.Domain.Accounts
or just
MyCompany.Core.Domain
For Visual Studio's way it would be the former. Also if you use lowercase file/folder naming you're looking at renaming the class each time, as well as making one big namespace tangle.
Most of it is common sense and really down to how you would expect to see the namespaces organised if you were a consumer of your own API or framework.
i was annoyed by this as well but working with and refactoring projects with large codebases quickly taught me otherwise. Having embraced the concept i think that it's a very good way to structure your code "physically" as well as logically. When you have a large project and the namespaces do not match up to the folders it becomes difficult to locate files quickly. It's also that much more difficult to remember where things are...
Also, if ReSharper recommends it, then it's probably a good idea. E.g. R# will complain if your class' namespace does not match its folder name.
File system folders and namespaces both represent a hierarchy. I seems perfectly natural to me to match the two. I go even one step further and use a 1:1 relationship between files and classes. I even do so when I program in other languages such as C++.
Now that you question the relation between these two hierarchies, I seriously wonder what you would like to represent by the file system hierarchy.
One way of not following the convention is to create the file in the project root folder and then move it to the final sub-folder.
Anyhow, it is a convention I actually like. If I am splitting types into folders, then probably those types have some kind of conceptual grouping related to the folder. Therefore, it ends making some sense, their namespaces are also similar. Java takes this approach and enforces it with its package system. The biggest difference is that VS is only "suggesting" it to you, since neither the language or the CLR enforces it.
While I agree with everyone else, that a physical structure matching the logical structure is helpful, I have to say I also fight with Visual Studio's auto-naming. There are half a dozen reasons why I have to rename classes:
I use a root "src" folder to visually separate my code from embedded resources
I want different capitalization
I'll organize my code into subfolders for organization within a namespace
I like to separate interfaces from implementations and base classes
I feel like it
With thiose reasons, I've resigned myself to having to adjust those for every class I create. My strategy to avoid the issue is copying a file that has the namespace declaration I want, and then immediately delete the contents.
I think there are indeed valid reasons for having different structures for namespaces and project folders. If you are developing a library, the namespace structure should first and foremost serve the users of your API: it should be logical and easy to grasp. On the other hand, the folder structure should be primarily there to make life easy for you, the API designer. Some goals are indeed very similar, like that the structure should be logical, too. But there may also be different ones, e.g. that you can quickly select related files for tooling, or that it is easy to navigate. I myself for example tend to create new folders when a certain file threshold is reached, otherwise it just takes too long to locate the file I'm looking for. But respecting the designer's preference can also mean strictly following the namespace - if that is their preference.
So overall, in many cases it makes sense that both match, but I think there are valid cases to deviate.
What has been helpful in the past for me was creating a file (e.g. WPF UserControl) in one place to get the namespace right and then moving it to the "right" folder.
Before namespaces were introduced in C++ all C types were in the global namespace. Namespaces were created to segregate types into logical containers so it was clear what type is being referred to. This also applies to C#.
Assemblies are a deployment decision. If you look at the .Net framework a given assembly will contain multiple different namespaces.
Folder are to organize files on disk.
The three have nothing to do with each other, however, it's often convenient that the assembly name, namespace and folder names are the same. Note that Java collapses folders and namespaces to be the same thing (limiting the developer's freedom to organize files and namespaces).
Often we choose to organize files in a project into multiple folders because it's easier for me or my team to navigate the files. Usually this file organization has nothing to do with the namespace design we use. I wish the VS team would not default the namespace to be the same as the folder name or at least give the option back to not have this be the default.
Don't suffer, either change the template for new classes or correct the namespace after the new file gets created.
I also feel the pain with this 'by default' behaviour in Visual Studio.
Visual Studio also tries to set a namespace/directory match when you put your LinqToSql .dbml files in their own directory. Whenever I edit the .dbml, I have to remember to:
open the .dbml.designer.cs file
remove the directory/folder name from the namespace declaration
There's a way to stop this behaviour, though. It involves creating a custom class template.
While I agree that matching the namespace hierarchy to the folder hierarchy is handy, and a good idea, I think the fact that Visual Studio doesn't seem to support switching this feature off is disgusting. Visual Studio has a lot of applications, and there are plenty of coding styles and ways of structuring the source file folders that are perfectly fine.
Let's say there's thousands of files that belong in a namespace, but the programmer just wants to group them into folders to make the hierarchy easier to navigate. Is this really such a bad idea? Will this really make things so un-maintainable that it should be forbidden by the IDE???
Let's say I'm using Visual Studio to work with Unity. Now, all my scripts are in the "Assets.Scripts" namespace. Not only is there a useless Assets namespace which contains no scripts now, but "Assets.Scripts" is meaningless - it does not describe what project or part of project the source file belongs to. Useless.
Assuming that the enum or struct is not nested within a particular class i.e. it belongs to the project namespace, should it be defined in:
Its own file
A general-purpose file called Enums.cs or Structs.cs where all the enums/structs that belong to the project namespace would be defined
Somewhere else...
Personally, I prefer the one type, one file philosophy. I even go so far as having nested types in separate files with partial classes used to allow the separation.
I mainly do this because I've seen far too much of the opposite. Single files that contain dozens of classes. The experience changed me.
For me, one type = one file, unless it's a delegate. I don't need to declare my own delegates very often these days due to Func and Action, but when I do I find it's useful to have a Delegates.cs file.
As for structs - I can only ever remember writing about two of them, aside from for the purposes of testing the evil things that mutable structs can do. But I'd stick to one per file there too. Why wouldn't you? Just because they're value types doesn't mean they're naturally shorter or simpler than classes. (Can you imagine if decimal and DateTime were both in the same source file? Eek!)
EDIT: I've just thought of another case where having multiple structs may be appropriate: interop. In that case I might have Interop.cs or Win32.cs... or possibly a namespace for it and back to one file per type.
This MSDN article on enum best practices makes no recommendation on where to store enum definitions.
You'll get different recommendations. Personally, I tend to store enums in the same file as the class they're related to. I like to keep my file structure the same as my namespace structure, as much as possible, and so if my enums naturally fall into a particular namespace, I'll store the definition in the corresponding file.
My suggestion is, find a scheme that works for you, and stick with it.
I put all of my enums in their own file. However, I also fully xml doccomment all of my types, including enums...so there are probably many more lines of code in my enum files than in most peoples.
I haven't written a struct in many, many years, but I don't consider them to be any less than a class (and again, I fully xml doccomment all of my types, structs included), so they have in the past always had their own file too.
When it comes to delegates, being as they are usually one liners (minus doccomment), I tend to keep them in the same file as whatever more prominent type they support. I don't often write delegates these days, but sometimes I find they still have a use. However, I try to keep any delegates declared at the top of the file, rather than nested or below the main type...makes em easier to spot when you go looking for them.
I think there is also a very simple but practical reason to keep each type in its own file. They are very EASY to spot that way. If you bury your enums and structs inside other types, or keep them within another file, sometimes (and don't assume you, and the people reading your code, always have access to Visual Studio and all of its rich tools) it can be quite difficult to find the type your looking for.
Do default parameters for methods violate Encapsulation?
What was the rationale behind not providing default parameters in C#?
I would take this as the "official" answer from Microsoft. However, default (and named) parameters will most definitely be available in C# 4.0.
No, it doesn't affect encapsulation in any way. It simply is not often necessary. Often, creating an overload which takes fewer arguments is a more flexible and cleaner solution, so C#'s designer simply did not see a reason to add the complexity of default parameters to the language.
Adding "Another way to do the same thing" is always a tradeoff. In some cases it may be convenient. But the more syntax you make legal, the more complex the language becomes to learn, and the more you may wall yourself in, preventing future extension. (Perhaps they'd one day come up with another extension to the language, which uses a similar syntax. Then that'd be impossible to add, because it'd conflict with the feature they added earlier)
As has been noted, default parameters were not a prioritized feature, but is likely to be added in C# 4.0. However, I believe there were excellent reasons not to include it earlier (in 4.0, as I've understood it, itäs mostly to support duck typing styles of programming where default parameters increases type compatibility).
I believe excessive parameter lists (certainly more than 4-5 distinct parameters) is a code smell. Default parameters are not evil in themselves, but risk encouraging poor design, delaying the refactoring into more objects.
To your first question - no, it's exactly the same as providing multiple overloaded constructors. As for the second, I couldn't say.
Default parameters will be included in C# 4.0
Some reading material about it:
click
click
It also seems that the author of this post will publish an article in the near future on the 'why' MS chooses to implement default params in C#
Here is an answer why it's not provided in C#
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx
One drawback with the default parameter implementation in C# 4.0 is that it creates a dependency on the parameters name. This already existed in VB, which could be one reason why they chose to implement it in 4.0.
Another drawback is that the default value depends on how you cast your object. You can read about it here: http://saftsack.fs.uni-bayreuth.de/~dun3/archives/optional-parameters-conclusion-treat-like-unsafe/216.html .