0

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

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.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112

1 Answers1

1

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);
    }
    ...
}
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151