Skip to content

Commit

Permalink
Add support for static get-only properties
Browse files Browse the repository at this point in the history
  • Loading branch information
NxSoftware committed May 22, 2024
1 parent 35cbdf3 commit ce50bdd
Showing 2 changed files with 54 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/CodeGenHelpers/PropertyBuilder.cs
Original file line number Diff line number Diff line change
@@ -118,7 +118,7 @@ public PropertyBuilder WithAccessModifier(Accessibility accessModifier)
AccessModifier = accessModifier;
return this;
}

public PropertyBuilder Override(bool @override = true)
{
_override = @override;
@@ -128,7 +128,11 @@ public PropertyBuilder Override(bool @override = true)
public PropertyBuilder MakeStatic()
{
IsStatic = true;
FieldTypeValue = FieldType.Const;
if (string.IsNullOrEmpty(_getterExpression))
{
FieldTypeValue = FieldType.Const;
}

return this;
}

@@ -167,6 +171,7 @@ public ClassBuilder UseAutoProps(Accessibility? setterAccessibility)
public PropertyBuilder WithGetterExpression(string expression)
{
_getterExpression = expression;
FieldTypeValue = FieldType.Property;
return this;
}

@@ -260,7 +265,7 @@ void IBuilder.Write(in CodeWriter writer)
{
FieldType.Const => $"{AccessModifier.Code()}{isNew} const {type} {name}",
FieldType.ReadOnly => $"{AccessModifier.Code()}{isNew}{_static} readonly {type} {name}",
_ => additionalModifier is null
_ => additionalModifier is null
? $"{AccessModifier.Code()}{isNew}{_static} {type} {name}"
: $"{AccessModifier.Code()} {additionalModifier} {type} {name}"
}).Trim();
46 changes: 46 additions & 0 deletions tests/CodeGenHelpers.Tests/Tests/PropertyTests.cs
Original file line number Diff line number Diff line change
@@ -174,6 +174,52 @@ partial class SampleClass
AreEqual(expected, builder);
}

[Fact]
public void AddsGetterExpressionToStaticProperty()
{
var builder = CodeBuilder.Create("AwesomeApp")
.AddClass("SampleClass")
.AddProperty("Test")
.MakePublicProperty()
.MakeStatic()
.SetType("string")
.WithGetterExpression("\"test\"")
.Class;

var expected = @"namespace AwesomeApp
{
partial class SampleClass
{
public static string Test => ""test"";
}
}
";
AreEqual(expected, builder);
}

[Fact]
public void AddsStaticToPropertyWithGetterExpression()
{
var builder = CodeBuilder.Create("AwesomeApp")
.AddClass("SampleClass")
.AddProperty("Test")
.MakePublicProperty()
.WithGetterExpression("\"test\"")
.MakeStatic()
.SetType("string")
.Class;

var expected = @"namespace AwesomeApp
{
partial class SampleClass
{
public static string Test => ""test"";
}
}
";
AreEqual(expected, builder);
}

private void AreEqual(string expected, ClassBuilder builder)
{
var expectedOutput = $@"//------------------------------------------------------------------------------

0 comments on commit ce50bdd

Please # to comment.