Can you create in C# a String array type property with 2 positions?

Asked

Viewed 686 times

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 am checking if the ModelState.isValid

Only I wanted the string array in the image list to be two positions. But I don’t know how to create this. My attempt was to create like this

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

But it doesn’t work, and I need the array to have 2 values inside.

  • How you are sending the array of Imagens of your Form if you send 2 items that are string array with the name Images is loaded automatically!? What’s at stake now is you put your form and explain what you’re doing. Ah the Controller also!

  • You want to create a array with two strings or wants a string that has only 2 characters? These characters are in which encoding?

2 answers

3


There is no native . NET type that represents a fixed size array, criticizing already in the compilation if it is exceeded.

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

Something like that:

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

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

}

However, I believe that this is not the best solution for what you are looking for. The most recommended in this case would be to build 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; }
}

0

You can create a custom validate sort of 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; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.