Can I create a 2-position string Array Property in C #?

0

I have the following properties in a model:

public List<string[]> Imagens { get; set; }

public string[] Video { get; set; }

public string[] Audio { get; set; }

There in my Controller I'm checking if ModelState.isValid

I just wanted the string array in the image list to have two positions. But I do not know how to create this. My attempt was to create this

public List<string[2]> Imagens { get; set; }

But it does not work, and I need the array to have 2 values inside.

    
asked by anonymous 09.11.2016 / 15:26

2 answers

3

There is no natively type in a .NET that represents an array of fixed size, criticizing already in the compilation if it is exceeded the limit of the same.

What you can do in this case is to initialize the fixed-size array in the constructor and prevent it from being overridden by another array by changing the setter scope of your property.

Something like this:

class MinhaClasse
{
    public string[] Imagens { get; private set; }

    public MinhaClasse()
    {
        this.Imagens = new string[2];
    }

}

I think, however, that this is not the best solution for what you are looking for. The most recommended one in this case would be to construct a class of its own that actually represents what this property represents.

Example:

class MinhaClasse
{
    public ConjuntoImagens Imagens { get; set; }
}

class ConjuntoImagens
{
    public string CaminhoImagemPequena { get; set; }
    public string CaminhoImagemGrande { get; set; }
}
    
09.11.2016 / 15:43
0

You can create a custom validate more or less like this:

public class MaxLengthArrayImgs : ValidationAttribute
{
    private readonly int _minElements;

    public MaxLengthArrayImgs (int minElements)
    {
        _minElements = minElements;
    }

    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            foreach (var item in list)
            {
                var arr = item as string[];
                if (arr.length > minElements)
                    return false;
            }
            return true;
        }
        return false;
    }
}


[MaxLengthArrayImgs(2, ErrorMessage = "OverFlow")]
public List<string[2]> Imagens { get; set; }
    
09.11.2016 / 20:06