Seph
Seph

Reputation: 8693

Option Strict and DefaultValueAttribute

Having just spent the past several hours trying to work out why my Xml Serialization code was not working. Consider the following:

<DefaultValueAttribute(False)>
Public Property UserName() As String

Why is this allowed regardless of option strict being on (or not)?

Upvotes: 0

Views: 182

Answers (2)

Seph
Seph

Reputation: 8693

The answer is that VS does not type check default values for VB.NET, regardless of OptionStrict or not.

<DefaultValueAttribute(False)> is valid because the attribute definition is really a constructor and not a type definition, as such it's type is DefaultValueAttribute and not a return type of boolean. Furthermore the .Value property of the DefaultValueAttribute is of type Object and hence it's type cannot be compared either, as such the very existence of DefaultValueAttribute violates Option Strict On and hence Option Strict ignored for the scope of DefaultValue Attributes.

Upvotes: 0

Alex Essilfie
Alex Essilfie

Reputation: 12613

Quite simple. The DefaultValueAttribute has an overload which accepts boolean values so it will work with or without Option Strict on.

Check this page for more information DefaultValueAttribute Class.

Upvotes: 1

Related Questions