Why is the struct allowed but the class isn't?

The error is CS8618 - Non-nullable variable must contain a non-null value when exiting constructor. Consider declaring it as nullable. The struct is readonly if that matters.
No description
27 Replies
phaseshift
phaseshift2mo ago
you need to init the struct It's not clear to me which struct you are referencing when saying a struct is allowed
ElectricTortoise
ElectricTortoiseOP2mo ago
oh struct is PositionInfo light green = struct green = class sorry i shouldve been clearer
phaseshift
phaseshift2mo ago
what are the members of BitBoard? And does it have a non-default ctor?
ElectricTortoise
ElectricTortoiseOP2mo ago
members?
phaseshift
phaseshift2mo ago
since it's readonly you must init it with the correct data to start with
ElectricTortoise
ElectricTortoiseOP2mo ago
PositionInfo is readonly, Bitboard is not
ElectricTortoise
ElectricTortoiseOP2mo ago
this is what Bitboard looks like
No description
phaseshift
phaseshift2mo ago
So class members dont get default init'd to any specific value. They stay as null unless to write code otherwise
ElectricTortoise
ElectricTortoiseOP2mo ago
ooo ok but structs do?
phaseshift
phaseshift2mo ago
(a member that is a class type)
ElectricTortoise
ElectricTortoiseOP2mo ago
ok or is it bcs the struct is readonly
phaseshift
phaseshift2mo ago
yeah, structs are always non-null
ElectricTortoise
ElectricTortoiseOP2mo ago
ah ok so Bitboard? will fix it?
phaseshift
phaseshift2mo ago
you can either let null be a valid state for it (not suggested) by changing the type to BitBoard?, or you can init it inline, BitBoard _bitboard = new();, or you can do similar in a constructor If BitBoard has constructor arguments then add them into new(...)
ElectricTortoise
ElectricTortoiseOP2mo ago
ooo ok whats inline btw
phaseshift
phaseshift2mo ago
BitBoard _bitboard = new(); it's what I'm calling that where the init is 'inline' with the member declaration
ElectricTortoise
ElectricTortoiseOP2mo ago
ooo ok what does the _ do in python it makes the field protected does it do anything in C#
glhays
glhays2mo ago
Does nothing, just a naming convention adopted by many.
ElectricTortoise
ElectricTortoiseOP2mo ago
ooo ok
phaseshift
phaseshift2mo ago
it doesnt do anything, just convention
ElectricTortoise
ElectricTortoiseOP2mo ago
wait but wouldnt my variable name be _bitboard instead of bitboard
glhays
glhays2mo ago
Yes
ElectricTortoise
ElectricTortoiseOP2mo ago
do i have to fix it later on? or do i just use _bitboard
phaseshift
phaseshift2mo ago
It would change the name, yes it needs to match everywhere. You dont need to change it
ElectricTortoise
ElectricTortoiseOP2mo ago
ok ty for the help
phaseshift
phaseshift2mo ago
👍
Anton
Anton2mo ago
The compiler does not check for null references in struct fields. You would be getting an error there as well, because you have an uninitialized reference type field in PositionInfo.

Did you find this page helpful?