I have a very basic question. In a Visual Studio project, I found two partial classes named Startup. The classes are in different files.
If I click on the first method (ConfigureAuth), it appears in the class file "Startup.Auth.cs". The second file appears in the class file "Startup.cs". How can I organize the classes like that?
You can use partial classes in C# to split a big class into several files. Refactoring a big class is often better but there are some legitimate reasons to have big classes.
Another use of partial classes is to allow a code generated class to be manually modified. The code generated part of the class goes into one file while the manual changes are kept in a separate file. In your case there is a single Startup
class that are built from seperate source files handling seperate parts of the startup. Some of these files can be added by NuGet packages and using a partial class greatly simplifices how different features are included in your application.
It is quite simple to split a class into several source files using partial
:
Assume you have a class implemented in the source file MyClass.cs
:
class MyClass {
public void MethodA() { ... }
public void MethodB() { ... }
}
You can then split it into two source files. MyClass.A.cs
:
partial class MyClass {
public void MethodA() { ... }
}
And MyClass.B.cs
:
partial class MyClass {
public void MethodB() { ... }
}
So by marking the class as partial
you are allowed to spread the contents of the class across several instances of class
constructs. The compiler will merge them all into a single class
definition during compilation.
You can study the details about partial classes on MSDN.