Skip to content

Commit

Permalink
Check if a type is a keyword before using short names.
Browse files Browse the repository at this point in the history
  • Loading branch information
las-nsc committed Jun 7, 2022
1 parent eea0fe0 commit 8f4769b
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions XmlSchemaClassGenerator/CodeUtilities.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using Microsoft.CSharp;

using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.Immutable;
Expand Down Expand Up @@ -172,7 +174,7 @@ public static string GetUniqueFieldName(this TypeModel typeModel, PropertyModel
var classModel = typeModel as ClassModel;
var propBackingFieldName = propertyModel.Name.ToBackingField(classModel?.Configuration.PrivateMemberPrefix);

if (!IsValidIdentifier(propBackingFieldName.ToLower()))
if (!CSharp.IsValidIdentifier(propBackingFieldName.ToLower()))
propBackingFieldName = "@" + propBackingFieldName;

if (classModel == null)
Expand Down Expand Up @@ -214,7 +216,7 @@ public static string GetUniquePropertyName(this TypeModel tm, string name)

internal static string NormalizeNewlines(string text) => NormalizeNewlinesRegex.Replace(text, "$1\r\n");

private static readonly Predicate<string> IsValidIdentifier = new Microsoft.CSharp.CSharpCodeProvider().IsValidIdentifier;
private static readonly CSharpCodeProvider CSharp = new();

internal static Uri CreateUri(string uri) => string.IsNullOrEmpty(uri) ? null : new Uri(uri);

Expand Down Expand Up @@ -255,7 +257,9 @@ public static bool IsUsingNamespace(string namespaceName, GeneratorConfiguration

public static CodeTypeReference CreateTypeReference(Type type, GeneratorConfiguration conf)
{
if (IsUsingNamespace(type.Namespace, conf))
// If the type is a keyword it will prefix it with an underscore to make it a valid identifier.
var isKeyword = CSharp.CreateValidIdentifier(CSharp.GetTypeOutput(new(type)))[0] == '_';
if (!isKeyword && IsUsingNamespace(type.Namespace, conf))
{
var typeRef = new CodeTypeReference(type.Name, conf.CodeTypeReferenceOptions);

Expand Down

0 comments on commit 8f4769b

Please sign in to comment.