/// <summary> /// Returns a compile-time constant default expression for the given type model. /// </summary> public static string GetTypeDefaultExpression(this ITypeModel typeModel) { if (typeModel.IsNonNullableClrValueType()) { return($"default({typeModel.GetCompilableTypeName()})"); } else { return("null"); } }
/// <summary> /// Returns a boolean expression that compares the given variable name to the given default value literal for inequality. /// </summary> public static string GetNotEqualToDefaultValueLiteralExpression(this ITypeModel typeModel, string variableName, string defaultValueLiteral) { if (typeModel.IsNonNullableClrValueType()) { // Structs are really weird. // Value types are not guaranteed to have an equality operator defined, so we can't just assume // that '==' will work, so we do a little reflection, and use the operator if it is defined. // otherwise, we assume that the operands are not equal no matter what. var notEqualMethod = typeModel.ClrType.GetMethod("op_Inequality", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (notEqualMethod is not null || typeModel.ClrType.IsPrimitive || typeModel.ClrType.IsEnum) { // Let's hope that != is implemented rationally! return($"{variableName} != {defaultValueLiteral}"); } else { // structs without an inequality overload have to be assumed to be not equal. return("true"); } }
/// <summary> /// Returns a boolean expression that compares the given variable name to the given default value literal for inequality. /// </summary> public static string GetNotEqualToDefaultValueLiteralExpression(this ITypeModel typeModel, string variableName, string defaultValueLiteral) { if (typeModel.IsNonNullableClrValueType()) { if (typeModel.ClrType.IsPrimitive || typeModel.ClrType.IsEnum) { // Let's hope that != is implemented rationally! return($"{variableName} != {defaultValueLiteral}"); } else { // We assume non-primitive structs are not equal. return("true"); } } else { // Nullable<T> and reference types are easy. return($"!({variableName} is {defaultValueLiteral})"); } }