can one make 'safe' arbitrary substr lengths?

JKnottJKnott Member ✭✭
edited September 7 in General

Hey all,
this should be a quick and easy one, I expect the answer is heck no, but why not ask...

Is there a way to make a nullable or some such safe attempt at using a strlen or substr length?

example:
If I wanted to make sure my data class never gave me a null I could do this...

public class data()
{
    private string myname;
    public string MyName
    {
        get => this.myname ?? string.empty;
    }
}

In that example, I will never get a MyName==null exception because it sends an empty string thus initializing the element.

Could I then do something like

 var something = $"{this.MyName?.Substring(0, 4)}.jpg";

I am looking for a shortcut to not have to do this

        string MyName = "hello World!";
        var something = $"{MyName.Substring(0, (MyName.Length <= 5 ? 5:MyName.Length))}.jpg";

It works, but I cant help but shake my head when I read that...

Anyhow if anyone knows of another way to do it, please let me know!

Cheers!

Sign In or Register to comment.