❔ Optional function parameter
I have this function
public void abc(Entity entity, List<string> directions, Position occupied = null
but I get CS1750: A type of value <null> cannot be used as a default parameter because there are no standard conversions to type Position
17 Replies
Is
Position
a struct?
In which case you could do Position? occupied = null
Yes
yeah structs can't be null
unless you have a
?
at the end which indicates that it's nullableCannot convert Position? to Position
Show your actual code
The error above came from
Position? x = null;
as a test
Crap it works if both types are ?
ThabksThinker
REPL Result: Success
Compile: 523.168ms | Execution: 74.427ms | React with ❌ to remove this embed.
works fine
I have the parameter
Position?
which works
I have an if statement to check if it is null, and in the else I assume its not null and use the properties. C# raises
error CS1061: Position? does not contain a definition for …
yeah you have to check that the value isn't null and then you can access
.Value
which is the actual valueThinker
REPL Result: Success
Console Output
Compile: 642.851ms | Execution: 86.451ms | React with ❌ to remove this embed.
It works but how come? What does the ? do?
Makes the type nullable
Structs cannot be null by themselves, so there's a special type called
Nullable<T>
which wraps around other structs and makes them able to be null.
Nullable<T>
looks a bit like this:
It has two properties, HasValue
which indicates whether the value is null or not, and Value
which is the actual wrapped value in case it's not null.
Position?
is just syntactic sugar for Nullable<Position>
So if you want a struct which can be null then you put a ?
at the end of it. Now you can access the value using .Value
, however you first need to make sure that the value actually exists, otherwise you'll get an exception.Ah very nice
Would you wrap a class in nullable
No because reference types can already be null
?
for reference types (classes, interfaces, etc.) is just a compiler annotation which marks them as possibly nullOkay, thank you
awesome explanation above
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.