In Java the file name must be the public class name defined in that java file. Does C# has similar requirement? can I have a A.cs file which only defines a public Class B inside? thanks,
-
1Yes, and you would be surprised how many C# projects still have the automatically created Class1.cs file, even though the class name was changed... – Michael Stum Feb 08 '10 at 20:35
-
2@Adam, Michael meant "no" to "Does C# has similar requirement?" but (correctly) "yes" to "can I have a A.cs file which only defines a public Class B inside?" – Kevin Feb 08 '10 at 20:43
-
@Adam I think he was just answering the second question in the text and not the first :) – Rune FS Feb 08 '10 at 20:43
-
partial classes can share EVERYTHING, just like they are in the same file? – 5YrsLaterDBA Feb 08 '10 at 20:57
-
This is not really an answer to the question, but I am wondering how I would get the name of the class in a file programmatically (through reflection) in the above case? – Samik R Jan 08 '11 at 00:21
4 Answers
No, there is no similar requirement.
Yes, you can do this.
It is considered bad practice, however.
Microsoft StyleCop will warn you if you do this, but everything will compile fine.

- 48,783
- 32
- 145
- 190
No, there is not a requirement that the filename matches a single public class being defined in the file. In fact, it is not necessary to have a relationship between the name of the containing file and any classes that are defined in the file. Implicit in this statement is that it is even possible to define more than one class in the same enclosing file (even if there are multiple classes that are public, unlike Java). Moreover, it is possible to define a class across multiple files using the partial
keyword.
Best practice, however, is to define one class per file and to give the file the same name as the class (or struct, etc.) being defined.

- 236,483
- 35
- 423
- 525
No, in C# you don't have to name your class the same as your file.
Along a similar line, you can have multiple public
classes in on file. Java only lets you have one.
This can be helpful for defining a few public enums in one file. Of a few small classes.
It is bad practice however to throw too much into one file.

- 136,852
- 53
- 295
- 323
It is possible to have a file A.cs
that contains public class B
but it is considered to be bad practice.

- 6,130
- 5
- 40
- 49