C
C#4mo ago
Nurglini

How do you declare an Array's Count property to be consistent within a Struct?

I'd like to make a struct with one of its variables being an array that's a consistent size, even if not all data points within that array are filled.
public struct Location
{
public string ID { get; set; }
public float[] Values { get; set; }
}
public struct Location
{
public string ID { get; set; }
public float[] Values { get; set; }
}
I would like my Values[]'s count property to be consistent, but I can't find a way to set that within the struct (say, all Locations will have an array of 10 Values). How could I do that?
12 Replies
Angius
Angius4mo ago
In the constructor
Jimmacle
Jimmacle4mo ago
make it get-only and initialize it in the constructor
Angius
Angius4mo ago
public struct Location
{
public string ID { get; set; }
public float[] Values { get; }

public Location(int size)
{
Values = new[size];
}
}
public struct Location
{
public string ID { get; set; }
public float[] Values { get; }

public Location(int size)
{
Values = new[size];
}
}
should do the trick
Marvin
Marvin4mo ago
i think you need new float[size]; at that scenario no?
MODiX
MODiX4mo ago
Angius
REPL Result: Failure
public struct Location
{
public float[] Values { get; }

public Location(int size)
{
Values = new[size];
}
}

var l = new Location(69);
public struct Location
{
public float[] Values { get; }

public Location(int size)
{
Values = new[size];
}
}

var l = new Location(69);
Exception: CompilationErrorException
- Invalid rank specifier: expected ',' or ']'
- { expected
- } expected
- No best type found for implicitly-typed array
- Invalid rank specifier: expected ',' or ']'
- { expected
- } expected
- No best type found for implicitly-typed array
Compile: 396.738ms | Execution: 0.000ms | React with ❌ to remove this embed.
Angius
Angius4mo ago
ye I guess the new[] doesn't work quite everywhere, mb
Nurglini
NurgliniOP4mo ago
Well, I still want to be able to set the Values, wouldn't this disallow that?
Angius
Angius4mo ago
It will prevent you from overriding the array. Say, doing loc.Values = new float[89267](); It will still let you set individual values, like loc.Values[4] = 420.69f;
Nurglini
NurgliniOP4mo ago
Mmm, but I could still do loc.Value[1] = n, kk, sweet
SleepWellPupper
SleepWellPupper4mo ago
Also, if you're new to C#, avoid using mutable structs, they can be a cause of great pain and suffering. Mutable structs are evil (generally)
Jimmacle
Jimmacle4mo ago
also, a struct with reference type members will work unexpectedly e.g. if you copy that struct, all copies will reference the same array
Marvin
Marvin4mo ago
yea that really took me off-guard when getting started back in the years
Want results from more Discord servers?
Add your server