Do properties always have a value when unset?

后端 未结 4 2039
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-18 03:04

I have a property like this:

public Tuple[] Breadcrumbs { get; set; }

and I have a test in one of my methods like thi

4条回答
  •  爱一瞬间的悲伤
    2021-01-18 03:39

    It's logically impossible for it not to have a value. It's going to have to return something, some bunch of 1s and 0s that is at least believed to be a reference to a Tuple[], so to that extent it has a value.

    It's also the case that all fields in classes get set to their default value (default(T) for whatever type T they are, which is null for all reference types). Otherwise it would be possible to have an object that was in a state that not only didn't make any sense in terms of what it does, but which didn't make any sense by the rules of what .NET expects objects to do. This includes the hidden fields behind automatic properties.

    Now, in some languages we can do the equivalent of this:

    public Tuple[] Breadcrumbs
    {
      get
      {
        Tuple[] whatIWillSend;
        return whatIWillSend;
      }
    }
    

    If this were allowed, whatIWillSend would have a value defined not by any concious decision on your part, but by what happened to be in memory at the time. It could be null, it could be a valid Tuple[] by sheer coincidence (but not the one you wanted to use!), it could be a Dictionary> that the runtime is now going to think is actually a Tuple[] (there goes the type-safety of the entire system), it could be a quarter of a decimal structure. (In the languages that allow such things, it could also be a well-known value that debuggers for such languages set in these cases precisely so to help find bugs caused by it).

    That's the closest thing we can get to a property not having a value. Note though that:

    1. It would still have a value, just not a meaningful value.
    2. We aren't allowed to do this in C# anyway.

提交回复
热议问题