Vivek Nuna
Vivek Nuna

Reputation: 1

How to implement partial class in different file for file scoped classes in C#?

With File scoped types in C# 11, It will not be possible to implement a partial class for a file scoped class in a different file.

Will this be an exception with the file-scoped classes? because it will lose the purpose of partial class in this way.

Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/file

Upvotes: 1

Views: 546

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112362

With code generators you typically create a partial class in one file and ask the code generator to add functionality to this partial class in another file.

The code generator might want to create helper types in this other file to support the added functionality. The name given to this helper type could conflict with one of your types or types created by another code generator. This is where the file modifier is helpful.

This modifier is not meant to be applied to the partial class itself.

MyClass.cs (your code):

[GenerateHelpFunction] // Ask the code generator to add a method
public partial class MyClass
{
    public void MyMethod()
    {
        var myText= new Text();
    }
}

file class Text // Your class
{
}

MyClass.generated.cs (added by source generator):

public partial class MyClass
{
    public void Help()
    {
        var sourceGeneratorsText = new Text();
        ...
    }
}

file class Text // Helper type created by code generator
{
}

Upvotes: 1

Related Questions