Search code examples
c#visual-studiosonarqubeimmutability

C# Use an immutable collection or reduce the accessibility of the field(s) 'CreateContactMapping'


I'm having a problem with a class in an old project and I don't know how to refactor this part, I get the following error message from sonarcube:

Use an immutable collection or reduce the accessibility of the field(s) 'CreateContactMapping'.Why is this an issue?

This is the piece of code

public static readonly Dictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping =
    new Dictionary<string, Func<UpdateContactServiceRequest, object>>
    {
        { "firstname", req => req.FirstName },
        { "lastname", req => req.LastName },
        { "full_name", req => req.FullName },
        { "email", req => req.Email },
        { "phone", req => req.Phone },
        { "date_of_birth", req => req.BirthDate },
        { "job_title", req => req.JobTitle },
        { "occupation", req => req.Occupation },
        { "renda", req => req.MonthlyIncome },
        { "lifecyclestage", req => req.LifeCycleStage },
        { "hs_lead_status", req => req.LeadStatus },
        { "ali_email_validated", req => req.EmailValidated },
        { "ali_sms_token_validated", req => req.CellphoneValidated },
        { "id_da_proposta_atual", req => req.CurrentProposalId },
        { "contact_type", req => req.ContactType }
    };

How best to solve this?


Solution

  • One solution could be to change Dictionary to ImmutableDictionary, then run .ToImmutableDictionary() after initializing the dictionary.

    public static readonly ImmutableDictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping =
        new Dictionary<string, Func<UpdateContactServiceRequest, object>>
        {
            { "firstname", req => req.FirstName },
            { "lastname", req => req.LastName },
            { "full_name", req => req.FullName },
            { "email", req => req.Email },
            { "phone", req => req.Phone },
            { "date_of_birth", req => req.BirthDate },
            { "job_title", req => req.JobTitle },
            { "occupation", req => req.Occupation },
            { "renda", req => req.MonthlyIncome },
            { "lifecyclestage", req => req.LifeCycleStage },
            { "hs_lead_status", req => req.LeadStatus },
            { "ali_email_validated", req => req.EmailValidated },
            { "ali_sms_token_validated", req => req.CellphoneValidated },
            { "id_da_proposta_atual", req => req.CurrentProposalId },
            { "contact_type", req => req.ContactType }
        }.ToImmutableDictionary();