473,241 Members | 1,666 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

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 5777
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
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
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
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
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
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
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
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
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
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
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...

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.