[Solved] C# limit length of a string

I have the following class:

public class VendorClass {         
    public int VendorID { get; set; }
    public string VendorName { get; set; }

The fields above match fields in the database table.
In the case of say VendorName, how do I give it a field width ?

VendorName maps to a field in the database which is varchar(15)

Enquirer: Nate Pet


Solution #1:

You can’t limit the length of the string but you can use properties with backing fields to achieve the desired result :

public class VendorClass
    public int VendorID {  get; set; }

    private string _vendorName;

    public string VendorName
        get { return _vendorName; }
            if (value.Length > 15)
                _vendorName = value.Substring(0,15);                    
            } else { 
                _vendorName = value;
Respondent: Nasreddine

Solution #2:

Strings in C# have almost-arbitrary length.

When loading from your database, it will automatically accommodate the actual string length. When saving to the database, your business logic, data layer or ORM (as appropriate) will need to ensure the proper maximum length.

Respondent: Eric J.

Solution #3:

A string can’t have a set length in C#. You will have to handle the db length through some other mechanism like validation. Can’t really tell you more without more details.

Respondent: BNL

Solution #4:

I would question why you would do this in c# code. However this link has a couple of ways around this. I suppose either truncation or taking a subsring is the best option. You could also make sure that the UI (or the model-view) takes care of details such as this.

Respondent: Daniel Casserly

Solution #5:

I am not sure exactly what you are asking, but if you want to know the maximum length of a string, this question can help you.

If you want to limit the number of characters entered, I would suggest that you use server-side validation and/or client-side validation.

Respondent: Xaisoft

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.