wakurth
wakurth

Reputation: 1644

.NET DefaultValue Property Attribute instantiate new custom object type

I'm trying to use the DefaultValue attribute to decorate a property in order to assert the value is defaulted as a new list of a typed object in the program. The failing code is as follows:

<DataContract()>
Partial Public Class MessageBaseResponse


#Region "Properties"

    <DataMember()>
    Public Property Header As Header


    <DataMember()>
    <DefaultValue(GetType(List(Of [Error])))>
    Public Property Errors As List(Of [Error])


    <DataMember()>
    <DefaultValue(GetType(List(Of Warning)))>
    Public Property Warnings As List(Of Warning)


#End Region

End Class

How to instantiate new lists as default property value using the DefaultValue attribute approach?

Upvotes: 1

Views: 1383

Answers (1)

LarsTech
LarsTech

Reputation: 81610

The DefaultValue attribute has more to do with serializing the data, not setting the actual default value of the property. The linked page notes:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

Try instantiating the lists with the "New" keyword:

Public Property Errors As New List(Of [Error])

Upvotes: 1

Related Questions