简体   繁体   中英

Can I evaluate a string in C#

I have to Pad a string and return it before I can do a Substring on the string. Is there a way I can evaluate the string after the padding and combine the two statements into 1 line?

This works

    string numberOfRecords = allRecords.Count().ToString().PadLeft(8, '0');
    numberOfRecords = numberOfRecords.Substring(numberOfRecords.Length-8,8);

But this does not

    string numberOfRecords = allRecords.Count().ToString();
    numberOfRecords = numberOfRecords.PadLeft(8, '0').Substring(numberOfRecords.Length-8,8);

string is immutable in C#. In the first case, you are doing PadLeft(8, '0') and assigning to numberOfRecords . So it contains updated value (with PadLeft ).

But in the second case, you are doing PadLeft but the value of numberOfRecords will be same. This will fail when you do numberOfRecords.Length which will be original value ( allRecords.Count().ToString() ) and may throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM