Skip to content

Code cleanup for System.ComponentModel.TypeConverter  #18754

@AlexGhiondea

Description

@AlexGhiondea

There are a couple of clean-up items for the newly ported code inside System.ComponentModel.TypeConverter. These are captured from PR dotnet/corefx#12081

  • Remove explicit base() from constructor calls
  • Replace explicitly implemented properties with auto-implemented properties when possible
  • Simplify members and properties with 1 lines of code to expression bodied members: protected virtual bool CanRaiseEvents => true;
    *Switch over to the ?. operator in C# for null checking:
//From
EventHandler handler = (EventHandler)_events[s_eventDisposed];
if (handler != null) handler(this, EventArgs.Empty);
//To
((EventHandler)_events[s_eventDisposed])?.Invoke(this, EventArgs.Empty);

//From
ISite s = _site;
return s == null ? null : s.Container;
//To
public IContainer Container => _site?.Container;
  • Switch to string interpolation instead of string concatenation
  • Remove unnecessary initialization (ie. Bool foo = false)
  • Replace empty arrays with Array.Empty()
  • Replace string literals with nameof wherever possible.
  • Simplify event handler declarations when no custom code is required
  • Introduce readonly modifier for sync objects.
  • Replace nongeneric collections with generic collections
  • Use foreach instead of manually writing the foreach logic.
  • Cache the char[] into a static readonly field (ie. new char[] { '' })
  • Simplify the CultureInfoMapper code:
private static class CultureInfoMapper
{
    // Dictionary of CultureInfo.DisplayName, CultureInfo.Name for cultures that have changed DisplayName over releases.
    // This is to workaround an issue with CultureInfoConverter that serializes DisplayName (fixing it would introduce breaking changes).
    private static readonly Dictionary<string, string> s_cultureInfoNameMap = CreateMap();

    private static Dictionary<string, string> CreateMap()
    {
        const int Count = 274;
        var result = new Dictionary<string, string>(Count)
        {
            { "Afrikaans", "af" },
            ...
        };
        Debug.Assert(result.Count == Count);
        return result;
    }

    public static string GetCultureInfoName(string cultureInfoDisplayName)
    {
        string name;
        return s_cultureInfoNameMap.TryGetValue(cultureInfoDisplayName, out name) ?
            name :
            cultureInfoDisplayName;
    }
}

Metadata

Metadata

Assignees

Labels

area-System.ComponentModelenhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributors

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions