Set the property size of type array

1

I have a property that is of type array. This array must 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 set a size by forcing an array of 7x4 to be passed, ie [7,4] ? I know that you can validate set but I think of something like C where you already define the size in the type declaration.     

asked by anonymous 18.04.2018 / 20:51

1 answer

2

This is not possible.

As you expect this property to be " setada " by the consumer of the code, the best alternative would be to validate in the%

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 in .NET Fiddle

As a matter of curiosity, you can define arrays with a fixed size in unsafe contexts. However, in addition to being highly recommended, it is not possible to do this with multidimensional arrays, in classes (only for struct ) and contain types outside of 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];
}
    
18.04.2018 / 21:05