Reputation: 531
This question is more a curiosity then anything...
Say there is a class like:
public class Foo{
public int? x {get; set;}
public int? y {get; set;}
}
And somewhere in the project instances were created:
var foo1= new Foo
{
x= 1;
y= 1;
};
var foo2= new Foo
{
x= 1;
y= 1;
};
If for some reason they wanted to check to see if the equal each other and set them to NULL
if they are and print to screen...
ex:
if(foo1.x == foo2.x)
foo1.x = null;
if(foo1.y == foo2.y)
foo1.y = null;
if(foo1 == null){
Console.WriteLine("foo1 is NULL");
}else{
Console.WriteLine("foo1 is not NULL");
}
Which would print?
The instance of foo1 exists, but all it's objects are set to NULL
. I'm new to the concept of nullable types so this struck a curiosity in me! (My Visual Studio is on the fritz or I'd test myself)
Upvotes: 1
Views: 89
Reputation:
I have two hands. If my two hands are empty, does that mean I do not exist?
An variable's null state does not depend on any of the properties of the instance it points at.
Upvotes: 5
Reputation: 2001
foo1
is still an instantiated object and so would not be null so Console.WriteLine("foo1 is not NULL");
would be executed.
If you really needed foo1 == null
to return true if x and y are null then you could override the ==
operator and the Equals()
method.
Upvotes: 0
Reputation: 1881
You will have the else exucuted foo1 is not NULL
, the object itself is not null, but the properties are.
you can set foo1
to null by foo1 = null
Upvotes: 0
Reputation: 3214
As you said, foo itself is still an instantiated object, regardless of the values of its member data, so the else statement would print.
Upvotes: 2