Reputation: 77
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 a compile-time errors,
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
}
}
Upvotes: 3
Views: 297
Reputation: 5862
You can't 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" };
}
Upvotes: 3
Reputation: 33417
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.
Upvotes: 6
Reputation: 63752
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" };
Upvotes: 4