Home > other >  How use const array with struct C#
How use const array with struct C#

Time:07-12

I need to use an array inside the C# struct. my part of the code is as follows,

This is how I defined Struct.

struct customerParameter
{
    public const string value1 = "zero";
    public const string value2 = "one";
    public const string value3 = "theree";
    public const string[] multivalues = { "india", "china", "japan" };
}

But above code makes compile-time error,

The expression being assigned to 'customerParameter.multivalues' must be constant.

I added the above array in a struct, I need to do the following sample code thing. I need to check if the array consists of the customerInput or not. What is the best way to handle this? how can I use Struct with Array to do this?

static void Main(string[] args)
{
    var customerInput = Console.ReadLine();
    if (customerInput == customerParameter.value1)
    {
       //do something
    }
    if (customerParameter.multivalues.Contains(customerInput))
    {
        //my code
    }
}

CodePudding user response:

You cannot use a constant. However, you can use a static read-only field which is similar:

public static readonly string[] multivalues = new []{ "india", "china", "japan" };

CodePudding user response:

IMO use readonly and constuctor like

public readonly string[] multivalues;

public customerParameter()
{
    multivalues = new[] { "india", "china", "japan" };
}

EDIT

Depending on your final goal and achievement.

If your struct is used as a configuration struct then static readonly IReadOnlyList<string> is one way to go.

If your struct is a model with default values, then the constructor way in my answer is the way to go. But that requires C# 10 and a newer version of C#. If you are using an older version of C# then again stick to static readonly IReadOnlyList<string> way.

CodePudding user response:

You cannot use a constant, In C# Const means it can be determined at the compile-time, which is why only very primitive types such as string, int and bool can be a const. So You can use IReadOnlyList, to represent a read-only collection of elements. ReadMore:

struct customerParameter
{
    public const string value1 = "zero";
    public const string value2 = "one";
    public const string value3 = "theree";
    public static readonly IReadOnlyList<string> MULTIVALUES = new[] { "india", "china", "japan" };
}
  • Related