Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove a few allocations from GridLengthTypeConverter #22095

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 36 additions & 5 deletions src/Controls/src/Core/GridLengthTypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,63 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var strValue = value?.ToString();
string s = value?.ToString();

if (strValue == null)
if (s is null)
{
return null;
}

strValue = strValue.Trim();
if (string.Compare(strValue, "auto", StringComparison.OrdinalIgnoreCase) == 0)
#if NETSTANDARD2_0_OR_GREATER
string strValue = s.Trim();
#else
ReadOnlySpan<char> strValue = s.AsSpan().Trim();
#endif

if (strValue.Equals("auto", StringComparison.OrdinalIgnoreCase))
{
return GridLength.Auto;
if (string.Compare(strValue, "*", StringComparison.OrdinalIgnoreCase) == 0)
}

if (strValue.Equals("*", StringComparison.OrdinalIgnoreCase))
{
return new GridLength(1, GridUnitType.Star);
}

#if NETSTANDARD2_0_OR_GREATER
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this "too much"?

if (strValue.EndsWith("*", StringComparison.Ordinal) && double.TryParse(strValue.Substring(0, strValue.Length - 1), NumberStyles.Number, CultureInfo.InvariantCulture, out var length))
#else
if (strValue.EndsWith("*", StringComparison.Ordinal) && double.TryParse(strValue[0..(strValue.Length - 1)], NumberStyles.Number, CultureInfo.InvariantCulture, out var length))
#endif
{
return new GridLength(length, GridUnitType.Star);
}

if (double.TryParse(strValue, NumberStyles.Number, CultureInfo.InvariantCulture, out length))
{
return new GridLength(length);
}

throw new FormatException();
}

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is not GridLength length)
{
throw new NotSupportedException();
}

if (length.IsAuto)
{
return "auto";
}

if (length.IsStar)
{
return $"{length.Value.ToString(CultureInfo.InvariantCulture)}*";
}

return $"{length.Value.ToString(CultureInfo.InvariantCulture)}";
}
}
Expand Down