Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do properties always have a value when unset?

I have a property like this:

public Tuple<String, String>[] Breadcrumbs { get; set; }

and I have a test in one of my methods like this:

if (Breadcrumbs != null && Breadcrumbs.Length > 0) { }

Depending on when this method is called, Breadcrumbs may not have been set. In one test, Breadcrumbs == null evaulates to true.

Will unset properties always have a value? (Will it always be null?)

like image 200
Oliver Avatar asked Jan 27 '12 14:01

Oliver


People also ask

What is the default value property?

The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created.

How does get set work?

Example explainedThe get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.


3 Answers

An automatically-implemented property which hasn't been explicitly set by any code will always have the default value for the property type - which is null for reference types. (For int it would be 0, for char it would be '\0' etc).

An automatically implemented property like this is just equivalent to:

private PropertyType property;
public PropertyType Property
{
    get { return property; }
    set { property = value; }
}

... except that the backing variable has an unspeakable name (you can't refer to it in code) so it will always start off with the default value for the type.

like image 61
Jon Skeet Avatar answered Oct 01 '22 17:10

Jon Skeet


Auto-properties use backing fields and are compiled to regular properties.

If the Property-Type is a reference type the value would be null, if not the value would be the default value.

like image 38
Gilad Naaman Avatar answered Oct 01 '22 18:10

Gilad Naaman


Class member variables (called fields), and thus backing variables of properties, are always initialized to their default value, if they are not initialized explicitly, which is null for reference types. The default value for all types is the value whose binary representation consists of all bits set to 0.

On the other hand, C# requires you to initialize local variables explicitly. These are: variables declared in methods, constructors and property accessors and out method parameters; i.e. they are treated as undefined until you assign them a value.

like image 28
Olivier Jacot-Descombes Avatar answered Oct 01 '22 18:10

Olivier Jacot-Descombes