0

So I know with normal properties you can give it a default value eg.

public int someMethod { get; } = 1;

So my question is it possible to do the same with an array property?

public int[] someMethod {get; } = ??

Thanks!

Tim
  • 57
  • 2
  • 6
  • 3
    Yes you can do it with an array, or any other data type. And what you type in is exactly the same as if it was some local variable. – gunr2171 Mar 22 '22 at 02:50
  • @gunr2171 thanks! That helped me. I just wasn't sure how to initialise the array without knowing the length of the array but the empty method worked a treat. Thanks – Tim Mar 22 '22 at 03:01

1 Answers1

1
public int[] someMethod {get; } = new int[] { 1, 2, 3, ... };
CorrieJanse
  • 2,374
  • 1
  • 6
  • 23
  • What if I don't know the length of the array? – Tim Mar 22 '22 at 02:59
  • 1
    You can't initialize an array without knowing the length of it. – gunr2171 Mar 22 '22 at 03:00
  • @gunr2171 you are implicitly specifying the length of the array when you are initializing the default values. https://dotnetfiddle.net/GaWNxE – CorrieJanse Mar 22 '22 at 03:07
  • Yeah, you either type a number in the square brackets, or you have a set number of elements in the curly braces. Either way, you have to know the length of the array when you initialize it. – gunr2171 Mar 22 '22 at 03:09
  • If you don't know the length, then List is a better choice. [Create List at compile time](https://stackoverflow.com/questions/793000/create-listint-with-values-at-compile-time) – OhmnioX Mar 22 '22 at 04:08