1

Here is my code and it gives red squiggly line under the variable of the array declaration, stating,

Fixed size buffer fields may only be members of struct

float is a value type, so I don't quite understand this message. What is the correct syntax to create public array of 13 elements (0 through 12; I ignore index 0)...

class clsUtility
{
    public int UtilityId { get; set; }
    public fixed float InterpolationFactorMonth[13];      // <-- HERE IS THE PROBLEM
}
3
  • 4
    The correct syntax is to declare it as an array of floats, and to allocate a 13-element array and assign to it, like this: public float[] InterpolationFactorMonth = new float[13];. As the error states, fixed arrays are only usable from structs, and usually only used with interop/marshalling scenarios where you need to pass the struct to some foreign unmanaged piece of code. Commented Dec 31, 2019 at 16:39
  • Lasse, yes. if you post as answer I will accept that...I thought that the fact that it is only 13 elements means its fixed. So fixed array is something else.... Commented Dec 31, 2019 at 16:41
  • 1
    You already have a good answer by Jon, there's no need to create another one. Commented Dec 31, 2019 at 16:42

2 Answers 2

9

If you want a fixed-sized array inline, that has to be declared within a struct, as per the compiler error. If you're actually happy with a reference to an array as normal, you need to differentiate between declaration and initialization. For example:

// Note: Utility isn't a great name either, but definitely lose the "cls" prefix.
class Utility
{
    public int UtilityId { get; set; }
    public float[] InterpolationFactorMonth { get; } = new float[13];
}

This declares a read-only property of type float[], and initializes it with a new array of 13 elements.

Sign up to request clarification or add additional context in comments.

Comments

2

So first of all, it is not possible to use fixed in this case. You could use public float[] InterpolationFactorMonth = new float[13]; To create an array of the size 13.

2 Comments

It is possible to use fixed for arrays, just not in classes.
Please read learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… - fixed size buffers definitely do exist. They're not quite the same as a regular array, but they use the same syntax, hence the error message the OP is seeing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.