1

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?

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. My current work around was - Public Property Errors As List(Of [Error]) = New List(Of [Error]) - which boils down to the same thing. I guess was just trying to see if there was a way to do it through an attribute, but you answer explains the details of that. Again, thanks @LarsTech

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.