C
C#2w 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
Angius2w ago
In the constructor
Jimmacle
Jimmacle2w ago
make it get-only and initialize it in the constructor
Angius
Angius2w 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
Marvin2w ago
i think you need new float[size]; at that scenario no?
MODiX
MODiX2w 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
Angius2w ago
ye I guess the new[] doesn't work quite everywhere, mb
Nurglini
Nurglini2w ago
Well, I still want to be able to set the Values, wouldn't this disallow that?
Angius
Angius2w 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
Nurglini2w ago
Mmm, but I could still do loc.Value[1] = n, kk, sweet
SleepWellPupper
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
Jimmacle2w 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
Marvin2w ago
yea that really took me off-guard when getting started back in the years
Want results from more Discord servers?
Add your server