getting warning: CS8618 - Non-nullable variable must contain a non-null value when exiting construct
I guess, it's not a big deal since the code is getting compiled but I still want to understand why I'm getting this warning and how can I resolve this. I was using a generic struct
29 Replies
With the code you've provided, what's stopping me from creating a
Rectangle<Rectangle<List<Rectangle<StringBuilder>>>>
?sanity?
So nothing, basically
That's the issue you're having
I can pass any nullable class as T
The actual error occurs because the compiler can't tell that
Length
and Width
aren't null if their corresponding fields aren't null.This is obviously a glaring issue, and is if I do pass a nullable type, then it's your responsibility to make sure
length
and width
are not null when the constructor exitsWhat you can do is either ignore the warning because it doesn't really matter in this case, or add
[NotNullWhenNotNull(nameof(length))]
to Length
, and the same for Width
.so what can I do to stop you?
This is because you explicitly specified those two to be non-null
Maybe constraint
T
to INumber<T>
if Ero thinks that's more saneYup, exactly that
INumber?
You may also consider using auto-properies for Length and Width
You may also consider renaming Length to Height
Basically so that
T
can only be a number, because using string
for length and height doesn't really make sense.
Should get you where you want
or
(if you prefer the full type over a record)
Although the record will also give you equality methods, which might be something you want
The type or namespace name 'INumber<>' could not be found
Is anyone surprised
Can you tell us what type of project you're making?
INumber
is in System.Numerics
so you'll have to import thatWhat tutorial are you following?
Do you know what .net version your project is using?
Yeah dotnet 7
Ah, that's good then
Importing System.Numerics should do it
well.. this is frustrating. I'm using INumber as
struct Rectangle <T> where T : INumber<T>
but the warning doesn't go away 😓Try
where T : unmanaged, INumber<T>
Might need to turn them around
I wonder if it's possible to just constrain it to notnull
instead of unmanaged
Though I think unmanaged
is a better fityeah that has nothing to do with the
INumber<T>
thing at all
again this is the actual issueright, so this error can't be removed?
If you were using auto-properties then it would go away
That's the easiest way
nvm. Yeah, its gone!
thanks both of you!
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.