int x
might not have an assignment. How do I detect that? What value does int hold when it is unassigned?
This gives me a warning in Visual Studio:
public SomeMethod(int x) {
if (x == null) {
/* VS throws a warning:
'The result of the expression is always 'false' since a value of type 'int'
is never equal to 'null' of type 'int' */
};
}
This also gives me a warning in Visual Studio:
public SomeMethod(int? x) {
// declaring int 'Nullable' does not fix the warning.
if (x == null) {
// Same warning.
};
}
Likewise:
public SomeMethod(int? x) {
if (!x.HasValue) {
// This does not work either.
};
}
int x might not have an assignment.
That's simply not true. In your case, x
is a parameter - it's "definitely assigned" from the start of the method, in specification terminology. When someone calls the method, they have to provide a value. There's no concept of the value not being assigned.
If you want to represent a parameter which may not have a meaningful int
value, you should use Nullable<int>
, aka int?
:
public void DoSomething(int? x)
{
if (x == null)
{
...
}
else
{
// Or whatever
Console.WriteLine(x.Value);
}
}
As of C# 4, you could then give the parameter a default value of null
if you want to be able to call it as just foo.DoSomething()
without providing a value. You couldn't distinguish between that and foo.DoSomething(null)
though.
See more on this question at Stackoverflow