Skip to content

Instantly share code, notes, and snippets.

@mamift
Last active September 23, 2019 23:00
Show Gist options
  • Save mamift/ef5195969c2a7be03637d4b844040242 to your computer and use it in GitHub Desktop.
Save mamift/ef5195969c2a7be03637d4b844040242 to your computer and use it in GitHub Desktop.
Extension method to add a get property that returns a default value (extends the CodeTypeDeclaration type).
public static class CodeDomExtensionMethods {
/// <summary>
/// Adds a get property that returns a default value.
/// </summary>
/// <param name="type"></param>
/// <param name="typeName"></param>
/// <param name="propertyName"></param>
/// <param name="attrs"></param>
/// <returns></returns>
public static CodeMemberProperty AddDefaultGetter(this CodeTypeDeclaration type, string typeName,
string propertyName, MemberAttributes attrs = MemberAttributes.Public)
{
if (typeName == null) throw new ArgumentNullException(nameof(typeName));
var tokenBaseType = new CodeTypeReference(new CodeTypeParameter(typeName));
if (typeName == "string" || typeName == "System.String")
tokenBaseType = new CodeTypeReference(typeof(string));
var defaultProperty = new CodeMemberProperty {
Type = tokenBaseType,
Name = propertyName,
Attributes = attrs,
HasGet = true
};
if (!attrs.HasFlag(MemberAttributes.Abstract)) {
defaultProperty.GetStatements.Add(new CodeMethodReturnStatement {
Expression = new CodeDefaultValueExpression {
Type = tokenBaseType
}
});
}
type.Members.Add(defaultProperty);
return defaultProperty;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment