Dave
Dave

Reputation: 177

Set attributes e.g. length for string

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?

Upvotes: 0

Views: 1953

Answers (2)

JTW
JTW

Reputation: 3685

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?

Upvotes: 1

MikeT
MikeT

Reputation: 5500

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

Upvotes: 2

Related Questions