473,503 Members | 13,285 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DefaultValue attribute on properties of user controls

Prior to C# 3.0, I would typically define a property of a custom user control
with pattern A:

=== PATTERN A ==========
private bool myBool = true;
public bool MyBool {
get { return myBool; }
set { myBool = value; }
}
======================

If this property exists in a custom user control, and I then instantiate
this user control in a WinForm, that property shows up in the visual designer
property pane with the default value I have assigned to the private backing
variable (in the above example, "true"). With the advent of C# 3.0, I want to
switch to the much more terse code in pattern B.

=== PATTERN B ==========
public bool MyBool { get; set; }
======================

Which raises the question of where to set the default. My first attempt was
to say "MyBool = true;" in the constructor of the custom user control. With
this technique, instantiating the control in a WinForm again shows my default
value for this property of the control in the property pane of the visual
designer.

I happened across what I thought was an even cleaner approach in the MSDN
documentation--the DefaultValue attribute so I tried pattern C:

=== PATTERN C ==========
[DefaultValue(true)]
public bool MyBool { get; set; }
======================

This compiles but does not work. That is, the MyBool property for this
control shows "false" in the property pane when instantiated on a WinForm.
(Note that my user control is in a library project and the WinForm is in a
WinForm project, both in the same solution. I first compiled the control
library, then dragged the control from the toolbox onto the WinForm so as to
avoid any stale designer-generated code.)

Should pattern C work? If so, what am I missing?

Environment: VS2008 with target=.NET 2.0 for both projects.
Jun 27 '08 #1
5 5816
Michael,

I don't know whether the pattern should work.

However, Google helped me find this one.
http://support.microsoft.com/kb/311339

HTH
Kalpesh
Jun 27 '08 #2
Hi Michael,

The pattern B you mentioned is called auto-implemented properties
introduced in C#3.0, which make property-declaration more concise in case
where no additional logic is required in the property accessors.

When you declare an auto-implemented property, the compiler creates a
private, anonymous backing field that is not accessible except through the
property's get and set accessors. Other than this, there isn't any
difference between an auto-implemented property and a normal property(by
the normal property, I mean the pattern A you mentioned).

If we set the value of a property in the constructor of the class or in the
declaration statement, the property is only initialized. Note, the default
value is NOT the initial value. If the value of the property equals to the
default value, the property's value is displayed in a regular font in the
Properties window and will not be serialized in the InitializeComponent
method of the Form; otherwise, shown in bold and will be serialized in the
InitializeComponent method.

To set a default value for a property, we can use the DefaultValueAttribute
on the property. And the default value specified by the
DefaultValueAttribute should equal to the initial value of the property.

A variable of type bool has an initial value of false. In your practice,
you don't set the MyBool property's value explicitly, so its initial value
is false. Then you specify the default value of the MyBool property is true
using the DefaultValueAttribute. When you add the UserControl on a form,
the value of the MyBool property shown in the Properties window is false
and in bold, because it doesn't equals to the specified default value.

Hope I make some clarifications.
If you have anything unclear, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
Jun 27 '08 #3
Thanks to both Linda and Kalpesh for useful information on this issue,
notably the distinction between default value and initial value. After
perusing the material, I believe Kalpesh is correct that pattern C does not
do what I want, i.e. initialize the property. So my conclusion, then, is that
pattern B is needed to set an initial value. I should have shown pattern B in
its entirety like this:

=== PATTERN B ==========
public MyObject {
public bool MyBool { get; set; }

public MyObject() { // constructor
MyBool = true;
. . .
}
}
======================

Linda, to followup on one of your comments, is there any particular
advantage for me to add the [DefaultValue(true)] in the code above so that it
does not get serialized in InitializeComponent?
Jun 27 '08 #4
Hi Michael,

Thank you for your quick reply!
is there any particular advantage for me to add the [DefaultValue(true)]
in the code above so that it does not get serialized in initializeComponent?

The DefaultValueAttribute is mainly used by designer. If the value of the
property equals to the default value, designer won't serialize this
property in code. This may make the initialization code concise.

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

This posting is provided "AS IS" with no warranties, and confers no rights.
Jun 27 '08 #5
Just to add - DefaultValueAttribute is also used by things like
XmlSerializer, and anything that uses System.ComponentModel, where
PropertyDescriptor.ShouldSerializeValue() and ResetValue() respect it,
at least for reflection-based maps.

Obviously we are talking about controls here, so yes: mainly the
designer - but it is supported in the wider context too.

Marc
Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
1871
by: Maurice Mertens | last post by:
Hi, I have an Access database in which I defined default values for certain columns. On my windows forms I've got controls bound to the dataset, The problem is that when I add a new row to the...
2
11418
by: timtos | last post by:
I want to set a color property of a user control by default. I am doing it like this: .... DefaultValue(typeof(System.Drawing.Color), "Blue"), .... The compiler likes it but my program...
5
1424
by: schneider | last post by:
Hello, Have an issue with a property using the DefaultValue(True) attribute. Imports System.ComponentModel Public Class Class1 Private m_testValue As Boolean
2
7863
by: Steve | last post by:
Hi, I would like to set the default value of a property on my control by: but can't because SystemColors.WindowText is not a constant. Microsoft controls do it, can I - is there a work round?...
6
1902
by: Meelis Lilbok | last post by:
Hi Why does property default value not work? When i start my application and dont set value from properties window the value is always "nothing". Whats the point off DefualtValue then? ...
10
3263
by: tony | last post by:
Hello!! I have some demo programs written in C# and they have this construction "" see below. I haven't seen this before so what does it mean ? public bool ShowDropDownButtons { get {...
4
5338
by: SteveT | last post by:
I have a boolean property that I want to serialize to disk using XmlSerializer. I noticed that if the property includes the attribute "DefaultValue(true)" or "DefaultValue(false)" that the...
6
9375
by: Peter Hartlén | last post by:
Hi! What's the correct syntax for the default value design time attribute, using classdiagram view and Custom Attributes dialog. For a boolean: DefaultValue(true) DefaultValue("true")...
1
1132
by: Olaf Rabbachin | last post by:
Hi folks, I'd like to retrieve default values for properties (of a user control) via code instead of having string-constants. Consider the following (simplified) property: Private _MyColor...
0
7212
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7364
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7470
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5604
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5026
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3186
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
405
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.