Why are objects apparently cloned by collection initializer for List<>?>
In the following code, why is pdList[0]
null while _propertyDetails
is a properly instantiated object? I was under the impression that I'm adding a reference to pdList
that points to the same object as _propertyDetails
, so after instantiating this object, both references should be non-null?
PropertyDetailsModel _propertyDetails = null;
var pdList = n开发者_如何学运维ew List<PropertyDetailsModel> { _propertyDetails };
_propertyDetails = PropertyDetailsModel.Read(PropertyId);
Forgive me if I'm missing something basic; I've been battling to narrow my problem down to this issue for several hours, and my brain is tired.
When you initialise the list, it is not _propertyDetails
that goes into the list, but the thing that _propertyDetails
is currently a reference to (which is null
in this example, but the point remains). Making _propertyDetails
refer to a different thing later doesn't change what's in the list.
It's (apparently) a reference type, so when you create pdList
, the reference gets copied, but it is null
at that point. Assigning to _propertyDetails
later does not change the null
reference that's already in pdList
.
_propertyDetails
is not an properly instantiated object. It's not an object at all. It is a reference which points to nothing which is called null
in C#. To get an object, you would have to write something like
PropertyDetailsModel _propertyDetails = new PropertyDetailsModel();
As others have said, you're getting confused between a variable and its value. You don't need to use lists to demonstrate this - it's equivalent to this code:
string foo = null;
string bar = foo;
foo = "Hello";
Console.WriteLine(bar); // Empty, as the value of bar is null
Changing the value of a variable is not the same thing as changing the data within an object that the variable refers to.
精彩评论