Ability to define nested class
Closed this issue · 7 comments
I have a requirement in my project, need to define a nested class. Is it an exiting feature?
Hey! Yeah you can use the class builder for that. Here is an example:
var @class = new ClassBuilder("MyClass", "MyNamespace")
.With(new ClassBuildMember(new ClassBuilder("MyNestedClass", "")
.BuildWithoutNamespace()))
.Build();
This will generate this
namespace MyNamespace
{
public class MyClass
{
public class MyNestedClass
{
}
}
}
Thanks a lot @MilleBo for the quick help.
I have one more question on this. Can we define a property as -
public string CustId { get; protected internal set; }
I have actually missed modifiers on get/set. It's pretty easy to add so I will do it later today and upload a new version for you.
You can also use roslyn directly as a workaround if you just want to try it (until I add it to my property class):
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
var @class = new ClassBuilder("MyClass", "MyNamespace")
.With(new ClassBuildMember(new ClassBuilder("MyNestedClass", "")
.WithProperties(PropertyDeclaration(
PredefinedType(
Token(SyntaxKind.StringKeyword)),
Identifier("CustId"))
.WithModifiers(
TokenList(
Token(SyntaxKind.PublicKeyword)))
.WithAccessorList(
AccessorList(
List<AccessorDeclarationSyntax>(
new AccessorDeclarationSyntax[]{
AccessorDeclaration(
SyntaxKind.GetAccessorDeclaration)
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken)),
AccessorDeclaration(
SyntaxKind.SetAccessorDeclaration)
.WithModifiers(
TokenList(
new []{
Token(SyntaxKind.ProtectedKeyword),
Token(SyntaxKind.InternalKeyword)}))
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken))}))))
.BuildWithoutNamespace()))
.Build();
Will generate
namespace MyNamespace
{
public class MyClass
{
public class MyNestedClass
{
public string CustId { get; protected internal set; }
}
}
}
Hey again,
I have just added a new nuget version (0.14.0). With it you can create your property like this:
var @class = new ClassBuilder("MyClass", "MyNamespace")
.With(new ClassBuildMember(new ClassBuilder("MyNestedClass", "")
.WithProperties(new AutoProperty("CustId", typeof(string), PropertyTypes.GetAndSet, new List<Modifiers> { Modifiers.Public }, setModifiers: new List<Modifiers> { Modifiers.Protected, Modifiers.Internal }))
.BuildWithoutNamespace()))
.Build();
Really Appreciate for quick turnaround !!.
Thanks a lot for you help.
No problem! Closing this one then. 👍