Is there another way or a proper way to use SubString()
Here is my sample:
var prefix = "OKA";
Console.WriteLine($"{prefix.Substring(0, 4)}");
// Result: Index and length must refer to a location within the string.Parameter name: length
So to avoid this exception I must write something like this:
var prefix = "OKA";
Console.WriteLine($"{prefix.Substring(0, prefix.Length > 4 ? 4 : prefix.Length)}");
// Result: OKA
This work but become difficult to read when you need to use this trick all the time in your code.
So I there something smart I can use like
var prefix = "OKA";
Console.WriteLine($"{prefix:XX}");
// XX is not working
I also try many alternative and documentation. My conclusion is there is no better solution or I need to write my own formatter but I would like to hear it from you.
Another way to avoid exceptions is to return null (or default) for most common error cases instead of throwing an exception. A common error case can be considered a normal flow of control. By returning null (or default) in these cases, you minimize the performance impact to an app.
The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.
C does not provide direct support for error handling (also known as exception handling). By convention, the programmer is expected to prevent errors from occurring in the first place, and test return values from functions.
C doesn't support exception handling. To throw an exception in C, you need to use something platform specific such as Win32's structured exception handling -- but to give any help with that, we'll need to know the platform you care about.
you could write an extension method that does the logic for you?
static class SomeHelperClass
{
public static string Truncate(this string value, int length)
=> (value != null && value.Length > length) ? value.Substring(0, length) : value;
}
and use
Console.WriteLine(prefix.Truncate(4));
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With