Cemal
Cemal

Reputation: 153

C# Create Const Array with multiple values at once

I have class like below;

public class PhoneNumbersDto
{            
 public string code { get; set; }
 public int dial { get; set; }
 public string mask { get; set; }
 public string name { get; set; }
}

And I have Values like below;

 {
    "code": "TR",
    "dial": 90,
    "mask": "### ### ## ##",
    "name": "Turkey"
  },
  {
    "code": "TM",
    "dial": 993,
    "mask": "## ######",
    "name": "Turkmenistan"
  },
  {
    "code": "TC",
    "dial": 1649,
    "mask": "### ####",
    "name": "Turks & Caicos Islands"
  }

I want to create a static const array with TheseClassType but i couldn't initilize it.

Is there a way to create static or const array with multiple values at once.

Thank you

Upvotes: 1

Views: 1426

Answers (1)

Sean Skelly
Sean Skelly

Reputation: 1324

    public static readonly PhoneNumbersDto[] array =
    {
        new PhoneNumbersDto()
        {
            code = "TR",
            dial = 90,
            mask = "### ### ## ##",
            name = "Turkey"
        },
        new PhoneNumbersDto()
        {
            code = "TM",
            dial = 993,
            mask = "## ######",
            name = "Turkmenistan"
        },
        new PhoneNumbersDto()
        {
            code = "TC",
            dial = 1649,
            mask = "### ####",
            name = "Turks & Caicos Islands"
        }
    }; 

As @eocron said, initialization can work; above is an example. Though for better style, I recommend that you use a constructor taking these four inputs, rather than the style shown.

readonly is used in place of const - you can only declare compile-time items as constants. readonly just means you can't edit the reference to this array.

Upvotes: 3

Related Questions