Set array type property size

Asked

Viewed 29 times

1

I have a property that is of type array. This array should have two dimensions being 7 rows and 4 columns, ie, Anytype[7.4], code:

public class WorkingDays
{
    public TimeSpan[,] Times { get; set; }

}

How do I fix a size, forcing a 7x4 array, ie [7,4]? I know it is possible to make validations on set but I think of something like C where you already set the size in the type declaration.

  • 2

    Not possible. You can validate in the method set or you can leave the instance ready and just let the "user" handle this matrix public TimeSpan[,] Times { get; } => new TimeSpan[7, 4];.

  • :(, then I have no choice but to validate set ?

  • 1

    That’s right. I was editing the comment.

1 answer

2


That is not possible.

How you intend this property to be "arrow" by the consumer of the code, the best alternative would be to validate in the method set of property

using System;

public class WorkingDays
{
    private TimeSpan[,] _times;

    public TimeSpan[,] Times
    {
        get { return _times; }
        set
        {
            if (value.GetLength(0) != 7 || value.GetLength(1) != 4)
                throw new Exception("Tamanho de matriz inválido");
            _times = value;
        }
    }
}

public class Program
{
    public static void Main()
    {
        var wd = new WorkingDays();
        try 
        {
            wd.Times = new TimeSpan[8, 4];
        }
        catch(Exception ex) 
        {
            Console.WriteLine(ex.Message); //Só pra não quebrar o exemplo
        }

        wd.Times = new TimeSpan[7, 4];
    }
}

See working on . NET Fiddle


By way of curiosity, it is possible to define arrays fixed size in contexts unsafe. However, in addition to being highly recommended, it is not possible to do this with arrays multidimensional, in classes (only for struct) and containing types outside the predefined.

An example:

void Main()
{
    var wd = new UWorkingDays();

    unsafe{
        Console.WriteLine(wd.Times[0]);
    }
}

public unsafe struct UWorkingDays
{   
    public fixed int Times[7];
}

Browser other questions tagged

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