0

If I am declaring a class in c#, can I set attributes such as string length?

e.g. say my class is:

public class MyClass
{
    public string SomeString1 {get; set;}
    public string AnotherString2 {get; set;}
}

Is there a way to specify that SomeString1 is only x Characters long?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Dave
  • 167
  • 17

2 Answers2

1

You can use the StringLengthAttribute in the .NET DataAnnotations class:

[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")] 
public string YourString { get; set; }

If you're working in MVC, these DataAnnotations will be validated on incoming requests and any error messages can be automatically displayed in your related view.

If you're not working in MVC, or just want to validate a class instance ad-hoc, you can use the Validator class: How to manually validate a model with attributes?

Community
  • 1
  • 1
JTW
  • 3,546
  • 8
  • 35
  • 49
  • 2
    Depends a lot on who is intended to gather the information. E.g. the core runtime does not limit a string length, no matter which attribute being attached. – Uwe Keim Mar 01 '17 at 12:42
  • 1
    only useful if they are using a technology that listens for DataAnnotations but otherwise good answer – MikeT Mar 01 '17 at 12:55
  • The Validator class can be used for ad-hoc validation in >= .net 4 as mentioned in my answer. – JTW Mar 01 '17 at 12:59
1

What you are asking for is validation, and there are several different validation routes available in the .net framework

some examples are IDataErrorInfo , INotifyDataErrorInfo and ValidationRule

which one is right for you depends on what you are doing

WPF is designed to automatically include these in views so provides some good examples such as here but they work just as well for manual validation tests

public class MyClass: IDataErrorInfo
{
    public string SomeString1 { get; set; }
    public string AnotherString2 { get; set; }

    public bool IsValid
        => string.IsNullOrWhiteSpace(Error);
    public string Error
        => this["All"];

    public string this[string field]
    {
        get
        {
            string err = "";
            if (field == "All" || "SomeString1" == field)
            {
                if (SomeString1.Length > 15)
                    err += "SomeString1 > 15";
                if (SomeString1.Length < 5)
                    err += "SomeString1 < 5";
            }
            if (field == "All" || nameof(AnotherString2) == field )
            {
                err += StringLenthRule(AnotherString2, nameof(AnotherString2), 30, 20);
            }
            return err;
        }
    }
    private string StringLenthRule(string str, string prop,int max, int min)
    {
        string err = "";
        if (str.Length > max)
            err += $"{prop} > {max}\n";
        if (str.Length < min)
            err += $"{prop} < {min}\n";
        return err;

    }
}

then you would do

MyClass node = new MyClass(xmlNode);

if(node.IsValid)
{
    //use class
}
else
{
    display(node.Error)
}
MikeT
  • 5,398
  • 3
  • 27
  • 43
  • thank you. the context is a web-service that would parse the xml file, and load each node into a database file. so i understand that i would be required to validate each node myself. – Dave Mar 01 '17 at 13:11
  • they general way would be to load the data into the class then check the validity this could be using `public bool IsValid =>string.IsNullOrWhiteSpace(IDataErrorInfo.Error)` that will then tell you if the class is valid and is not the Error property will identity the issue, you can use this for rejecting the xml or automated/manual correction – MikeT Mar 01 '17 at 13:18