Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to cleanly test and truncate string properties

I have the following code:

public void EnsureFieldLengths(SubmissionRequest request)
{
    TestAndTruncate(request?.ApplicationSubmission?.Applicant?.Address?.Line1, 60);
}

public void TestAndTruncate(string field, int maxLength)
{
    if(field != null)
    {
        field = field.Left(maxLength);
    }
}

Left() is an extension method off string to do the truncation. The above obviously doesn’t work, as the property is not passed by ref and thus setting field doesn’t make it back to the actual property.

I’m fully aware how to resolve this doing something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if(longProperty != null)
{
    longProperty = longProperty.Left(60);
}

However, I’m curious if I can solve this in a more readable manner, having to only type out longProperty once. I have 20-30 of these fields, and it would make it more readable to have a one-liner. I thought a ref parameter would work, but properties cannot be passed as ref.

Again, there is no problem doing the ‘long hand’ implementation of this, I’m just interested to see if someone smarter than me knows of a way to do this, without using reflection.

>Solution :

I suspect the cleanest option might be to use C#9 pattern matching:

if (request?.ApplicationSubmission?.Applicant?.Address is { Line1: { Length: > 60 } line1 } address)
{
    address.Line1 = line1.Substring(0, 60);
}

Or, if you need to process multiple properties on the address:

if (request?.ApplicationSubmission?.Applicant?.Address is {} address)
{
    if (address.Line1 is { Length: > 60 } line1)
    {
        address.Line1 = line1.Substring(0, 60);
    }
    if (address.Line2 is { Length: > 60 } line2)
    {
        address.Line2 = line2.Substring(0, 60);
    }
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading