user405783
user405783

Reputation:

Do all objects have a default value?

Do all objects have a default value?

Example;

Guid guid = default(Guid);

Gives; 00000000-0000-0000-0000-000000000000

DateTime dt = default(DateTime);

Gives; 01/01/0001 00:00:00

Is this true for all objects, do all objects give some value as a default? I'm right in assuming yes...?

Upvotes: 1

Views: 429

Answers (5)

Eric Lippert
Eric Lippert

Reputation: 659956

Do all objects have a default value?

Absolutely not. For example, the string "abc" is an object, but it does not have a "default value". The number 12 is an object, but it does not have a "default value".

However, all types have a default value. Remember, objects are instances of types; objects exist at runtime. Types are a compile-time concept. Do not confuse types with objects; they are as different as the string "The New York Times" and an actual copy of today's New York Times.

Values that may be stored in a variable of reference type are either references to objects or null. Hence the name "reference type": a value of a variable of reference type is a reference (or null).

Values that may be stored in a variable of value type are objects that are the values of that type. Hence the name "value type" - the value of a variable of value type is a value.

(I omit pointer types from the discussion; for our purposes, assume that all pointer types are logically the same as the value type IntPtr.)

The default value of any reference type is the null reference value.

The default value of any numeric value type - int, decimal, and so on - is the zero of that type. (Types that support multiple representations of zero, like float, choose the positive zero.) The default value of bool is false. The default value of any nullable value type is the null value of that value type.

The default value of any other value type is recursively defined as the value of that type formed by setting all of the fields of the type to their default values.

Is that clear?

Upvotes: 12

Fadrian Sudaman
Fadrian Sudaman

Reputation: 6465

Yes. Value types will have default value as defined. Numeric value is default to 0, and boolean is default to false. See here for more details http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

Reference type will be default to null.

Upvotes: 1

LiamB
LiamB

Reputation: 18586

"return null for reference types and zero for numeric value types."

http://msdn.microsoft.com/en-us/library/xwth0h0d%28v=VS.80%29.aspx

Might help explain a little more.

Upvotes: 5

stuartd
stuartd

Reputation: 73243

Yes. Reference types default to null, and Value types - like those you mention - default to specific values equating to zero.

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

The default for reference types is null.

Upvotes: 0

Related Questions