Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Default property value

3 views
Skip to first unread message

shapper

unread,
Oct 12, 2006, 8:00:09 AM10/12/06
to
Hello,

I am creating a class where I have various properties.
How to I set a default property value in case the property is not
defined by the user.

For example, I have the property:

' Priority
Public Property Priority() As Mail.MailPriority
Get
Return _Priority
End Get
Set(ByVal value As Mail.MailPriority)
_Priority = value
End Set
End Property

I want to set it to Mail.MailPriority.Normal in case the user didn't
defined it.

How can I do this?

Thanks,
Miguel

apathetic

unread,
Oct 12, 2006, 8:08:27 AM10/12/06
to
> How to I set a default property value in case the property is not
> defined by the user.

You are storing the actual value of the property in the _Priority
field, so you would just set an initial value for this variable when
it's declared:

Dim _Priority As Mail.MailPriority = Mail.MailPriority.Normal

(I think this is the VB syntax, I'm a bit rusty.)

Tim

Robert Haken [MVP]

unread,
Oct 12, 2006, 8:13:09 AM10/12/06
to

Basically, there are two techniques with lots of variations, early
initialization and late initialization:

Early initialization initializes the value when it is declared, or in
constructor:

private Mail.MailPriority _priority = Mail.MailPriority.Normal;
-or-
public Class()
{
_priority = Mail.MailPriority.Normal;
}

Late initialization initializes the value within first use:

public Mail.MailPriority Priority
{
get
{
if (_priority == null)
{
_priority = Mail.MailPriority.Normal;
}
return _priority;
}
...
}

Robert Haken [MVP ASP/ASP.NET]
HAVIT, s.r.o., www.havit.cz
http://knowledge-base.havit.cz


Morten Wennevik

unread,
Oct 12, 2006, 8:18:45 AM10/12/06
to
You could also use the DefaultValueAttribute. The effect would be the
same.

<DefaultValue(Mail.MailPriority.Normal)>


Public Property Priority() As Mail.MailPriority
Get
Return _Priority
End Get
Set(ByVal value As Mail.MailPriority)
_Priority = value
End Set
End Property

On Thu, 12 Oct 2006 14:08:27 +0200, apathetic <apathet...@gmail.com>
wrote:

--
Happy Coding!
Morten Wennevik [C# MVP]

shapper

unread,
Oct 12, 2006, 9:48:59 AM10/12/06
to
Hi Morten,

That was exactly what I was trying but I wasn't able to make it work.
Now I did made it work using:

<DefaultValue(Mail.MailPriority.Normal)> _


Public Property Priority() As Mail.MailPriority

I added the '_' at the end of DefaultValue code line.

Thanks,
Miguel

0 new messages