Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid exception with C# Substring() method? [duplicate]

Tags:

string

c#

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.

like image 667
Bastien Vandamme Avatar asked Jan 09 '18 11:01

Bastien Vandamme


People also ask

How do I avoid exceptions?

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.

How do you handle exception in C?

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.

Does C language have exception handling?

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.

Can C throw exceptions?

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.


1 Answers

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));

?

like image 89
Marc Gravell Avatar answered Oct 20 '22 20:10

Marc Gravell