C# .cs file name and class name need to be matched?

5YrsLaterDBA picture 5YrsLaterDBA · Feb 8, 2010 · Viewed 14k times · Source

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,

Answer

jason picture jason · Feb 8, 2010

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.