|
-
Jan 12th, 2010, 12:44 PM
#1
Thread Starter
Lively Member
[RESOLVED] Default Property Values
What is the difference between these two methods for defining property value defaults?
Code:
Public intSomeInt As Integer
Public strSomeString As String
Public objSomeObject As Object
Public booTrueFalse As Boolean
Sub New()
intSomeInt = 100
strSomeString = "DefaultString"
objSomeObject = strSomeString
booTrueFalse = True
End Sub
Code:
Public intSomeInt As Integer = 100
Public strSomeString As String = "DefaultString"
Public objSomeObject As Object = strSomeString
Public booTrueFalse As Boolean = True
Sub New()
'Constructor code here
End Sub
Is there a reason to use one method over the other for defining the default property values in a class?
-
Jan 12th, 2010, 12:50 PM
#2
Re: Default Property Values
If you had multiple constructors, you would have a bunch of duplicate code.
That is the very essence of human beings and our very unique capability to perform complex reasoning and actually use our perception to further our understanding of things. We like to solve problems. -Kleinma
Does your code in post #46 look like my code in #45? No, it doesn't. Therefore, wrong is how it looks. - jmcilhinney
-
Jan 12th, 2010, 12:59 PM
#3
Re: Default Property Values
as Bill said, it could lead to code duplication if you init the values in the constructor. In reality at runtime, the values are assigned when the constructor is called anyway. There is a readability factor when giving them values where declared. You don't have to go look at the constructor to see what values were given by default, you just look at the declarations.
One other side note is that those are not actually "properties" at all, they are "fields". A property uses property syntax of
Code:
Private _someInt as Integer = 100
Public Property SomeInt() as Integer
Get
return _someInt
End Get
Set(Value as integer)
_someInt = value
End Set
End Property
or in VB10 we can now do
Code:
Public Property SomeInt as Integer = 100
and it is the same as the first piece of code I posted.
The main difference between fields and properties is that properties support databinding and fields do not, and properties can contain validation logic, where fields are just straight variables.
-
Jan 12th, 2010, 02:41 PM
#4
Re: Default Property Values
Since we're getting semantic, I should point out that you are talking about initial values, not default values. A default value (only for properties) is the value that the IDE gives your property when you rightclick it in the properties list and select "Reset". You set the default value by using the DefaultValue attribute:
vb.net Code:
Private _Value As Integer Private _Visible As Boolean <DefaultValue(5)> _ Public Property Value() As Integer Get Return _Value End Get Set(ByVal value As Integer) _Value = value End Set End Property 'or <DefaultValue(GetType(Boolean), "True")> _ Public Property Visible() As Boolean Get Return _Visible End Get Set(ByVal value As Boolean) _Visible= value End Set End Property
-
Jan 12th, 2010, 04:26 PM
#5
Thread Starter
Lively Member
Re: Default Property Values
My example code was hastily constructed to illustrate my question.
For some reason, I was under the impression that it was generally more accepted to put the initial values in the constructor. Not sure why - probably just the examples that I have seen. But, it seemed more cumbersome and error prone this way. Hence, I figured I better ask 
What would be the use for the DefaultValue property, aside from where a property grid may be used? Going back to readability, if all the fields had their initial values set in a declarations section, this would be preferred, correct?
-
Jan 12th, 2010, 04:35 PM
#6
Fanatic Member
Re: Default Property Values
 Originally Posted by kleinma
or in VB10 we can now do
Code:
Public Property SomeInt as Integer = 100
wow i like that and am tempted to go to VS2010 because of it, I have spent hours doing all them return _blah, _blah = blah things in my 2008 classes
If debugging is the process of removing bugs, then programming must be the process of putting them in.
-
Jan 12th, 2010, 04:46 PM
#7
Re: Default Property Values
well you know you could just type the word property and then hit tab in VS2008 to use the snippet feature. It isn't AS good as auto props in VS2010, but it is a close second.
-
Jan 12th, 2010, 04:58 PM
#8
Fanatic Member
Re: Default Property Values
tbh i find the snippet way harder than using class details and a class diagram but yeah this 2010 feature is very useful, the majority of my properties are of the standard type that is shorthand for, but we digress...
If debugging is the process of removing bugs, then programming must be the process of putting them in.
-
Jan 12th, 2010, 05:12 PM
#9
Re: Default Property Values
The new feature in VS2010 still even creates a private backing field with the underscore prefix (you just don't see it in your code).
You also get databinding support still. So really the only time you need full properties in VS2010 now is when you need logic in your getter/setter, or if you need read only/write only properties.
-
Jan 12th, 2010, 05:31 PM
#10
Re: Default Property Values
 Originally Posted by wolfpackmars2
What would be the use for the DefaultValue property, aside from where a property grid may be used?
Not much really, except if you created a UserControl / custom control / component that you rely on heavily and want to add some user-friendliness to it. If 'where a property grid may be used' you mean dropping a PropertyGrid control on your form, then I'm not even sure if the DefaultValue attribute can be used, because the PropertyGrid does not show the context menu. I suppose you can add your own context menu, but then I'm not sure how to call the functionality that the Reset feature usually provides.
So basically it is just to make the design-time easier for your own custom controls.
 Originally Posted by kleinma
So really the only time you need full properties in VS2010 now is when you need logic in your getter/setter, or if you need read only/write only properties.
Can't you just use ReadOnly?
vb.net Code:
Public ReadOnly Property Value() As Integer
Shouldn't that just create a read-only automated property?
I think you do need to use full properties if you need different access modifiers on the getter and setter (or is that possible even with auto-implemented properties?).
If you can't, then I must say I like C#'s way much better:
csharp Code:
// read-only: public int Value { get; } // private set; public get: public int Value { get; private set; }
That said, I'm not sure how it would be possible to implement this behavior for VB without breaking all formatting rules... Perhaps something like
vb.net Code:
Public Property Value() As Integer { Get, Private Set } Public Property Value() As Integer With Get, Private Set Public Property Value() As Integer With { Get, Private Set } Public Property Value() As Integer Get Private Set End Property
Meh?
Last edited by NickThissen; Jan 12th, 2010 at 05:38 PM.
-
Jan 12th, 2010, 06:03 PM
#11
Re: Default Property Values
 Originally Posted by NickThissen
Can't you just use ReadOnly?
vb.net Code:
Public ReadOnly Property Value() As Integer
Shouldn't that just create a read-only automated property?
If that were possible, what is that property returning when you call it?
-
Jan 12th, 2010, 06:09 PM
#12
Re: Default Property Values
 Originally Posted by kleinma
If that were possible, what is that property returning when you call it? 
Hmm... Do you mean because you can never assign a value anymore? That makes sense lol. Perhaps like this
vb.net Code:
Public ReadOnly Property Value() As Integer = 15
or using the constructor
vb.net Code:
Public ReadOnly Property Value() As Integer Public Sub New() Me.Value = 12 End Sub
This is perfectly valid for fields, so why not properties?
Sure, you can never change it after that, and I can't really think of any use for that, but there are also ReadOnly fields that you can set like this, so why not?
Well it does make sense I suppose. An automated ReadOnly property would have no advantage over a ReadOnly field, (except perhaps databinding? Not sure how much sense that makes for read only properties, haha).
-
Jan 12th, 2010, 06:28 PM
#13
Re: Default Property Values
To answer the original question, setting field values where they're declared can be optimised by the compiler, so it's preferred over setting in the constructor, which can't be optimised.
If you do choose to set in the constructor for some reason, and there could be valid reasons, then code duplication isn't an issue. You simply put the code in the default constructor and then invoke that from the others. If that's not possible for some reason, you simply create an Initialise method and set the field values there, calling that method from wherever it's appropriate.
-
Jan 12th, 2010, 06:45 PM
#14
Re: Default Property Values
 Originally Posted by jmcilhinney
To answer the original question, setting field values where they're declared can be optimised by the compiler, so it's preferred over setting in the constructor, which can't be optimised.
John, out of curiosity, what to your knowledge gets optimized by the compiler in the different scenarios?
Given these 2 classes (both containing a value type and reference type), they produce identical IL ctors.
Code:
Public Class Class1
Private _TestString As String = "HELLO WORLD"
Private _Value As Integer = 10
Public Sub New()
End Sub
Public Property TestString() As String
Get
Return _TestString
End Get
Set(ByVal value As String)
_TestString = value
End Set
End Property
Public Property Value() As Integer
Get
Return _Value
End Get
Set(ByVal value As Integer)
_Value = value
End Set
End Property
End Class
Public Class Class2
Private _TestString As String
Private _Value As Integer
Public Sub New()
_TestString = "HELLO WORLD"
_Value = 10
End Sub
Public Property TestString() As String
Get
Return _TestString
End Get
Set(ByVal value As String)
_TestString = value
End Set
End Property
Public Property Value() As Integer
Get
Return _Value
End Get
Set(ByVal value As Integer)
_Value = value
End Set
End Property
End Class
-
Jan 12th, 2010, 06:54 PM
#15
Re: Default Property Values
 Originally Posted by kleinma
John, out of curiosity, what to your knowledge gets optimized by the compiler in the different scenarios?
Hmmm... I don't actually know. I just read that somewhere reputable some time ago, but never investigated further.
One point to consider with your testing: did you compile with optimisations enabled? Remember that optimisations are disabled by default for a Debug build.
-
Jan 12th, 2010, 07:09 PM
#16
Re: Default Property Values
Yes they are still identical in a release build. It could be in certain very specific scenarios that certain optimizations are used when possible I suppose.
-
Jan 12th, 2010, 07:22 PM
#17
Re: Default Property Values
 Originally Posted by kleinma
Yes they are still identical in a release build. It could be in certain very specific scenarios that certain optimizations are used when possible I suppose.
Hmmm... or maybe the source wasn't as reputable as I thought. Can't recall where it was now as it was some time ago. Perhaps I've been deluding myself all this time. Maybe I'm not handsome and cool either!
-
Jan 12th, 2010, 07:40 PM
#18
Re: Default Property Values
lol.
Well just so we can at least say one thing you SHOULDN'T do in terms of making it optimized, is to do something like this:
Code:
Private _TestString As String = ""
Private _Value As Integer = 0
Public Sub New()
_TestString = "HELLO WORLD"
_Value = 10
End Sub
which does effectively initialize the variables twice in the constructor.
-
Jan 12th, 2010, 07:54 PM
#19
Thread Starter
Lively Member
Re: Default Property Values
Thanks all for the responses. Exactly the information I was looking for.
2 final parting questions.
1) What could I have possibly done on my own to find this information for myself?
2) It is safe to assume that values will be initialized in the declarations before the constructor is called?
For example, if you have a field called "_FileName" with a default value set in the declarations, and a constructor with an optional "FileName" field where the user can optionally specify their own filename when creating a new instance of the class, it is safe to say that the default value in the declarations would not be able to overwrite the value set in the constructor.
I think this is fairly obvious, but just to eliminate any doubt...
-
Jan 12th, 2010, 08:05 PM
#20
Re: Default Property Values
 Originally Posted by wolfpackmars2
1) What could I have possibly done on my own to find this information for myself?
Searched MSDN and the web using appropriate keywords. The appropriate keywords may not be immediately apparent but, as you search and read, you can refine your search terms. Words like "constructor" and "initialize" would figure heavily.
 Originally Posted by wolfpackmars2
2) It is safe to assume that values will be initialized in the declarations before the constructor is called?
Declarations MUST be processed before the constructor. If you initialise a field where it's declared then that assignment will also be performed before the constructor.
-
Jan 12th, 2010, 08:06 PM
#21
Re: Default Property Values
1) MSDN documentation or a book on the language would provide information like this. (or ask on vbforums )
2) in reality, no assignments can be made outside of a method/property. So when you declare a variable at the class level, and give it a value where you declare it, that value assignment is actually going to be done in the constructor when the code actually runs.
-
Jan 12th, 2010, 08:08 PM
#22
Re: Default Property Values
 Originally Posted by kleinma
Yes they are still identical in a release build. It could be in certain very specific scenarios that certain optimizations are used when possible I suppose.
You know, now that I think about it, maybe I was remembering incorrectly. I now have an inkling that the advice was to initialise a field in the constructor or on a declaration, which can both be optimised, rather than elsewhere, e.g. a Load event handler, which can't. I guess I'll never know for sure as I doubt I'd ever find the original source but I might investigate a bit to see what I can find on the subject.
-
Jan 12th, 2010, 08:22 PM
#23
Re: Default Property Values
 Originally Posted by kleinma
2) in reality, no assignments can be made outside of a method/property. So when you declare a variable at the class level, and give it a value where you declare it, that value assignment is actually going to be done in the constructor when the code actually runs.
That really is more correct than what I posted. I guess I was talking in a source code sense but, even then, I guess what I said is still not completely correct. For instance, placing breakpoints on lines 3, 5 & 6 of this code:
vb.net Code:
Public Class Class1
Private number As Integer = 100
Public Sub New()
Dim x As Integer = 200
End Sub
End Class
reveals that line 5 is executed first, then line 3, then line 6. I guess the MSIL code would show exactly what happens. I really do need to make a point of disassembling more often, compared to my current which is pretty much not at all.
-
Jan 20th, 2010, 11:31 AM
#24
Thread Starter
Lively Member
Re: [RESOLVED] Default Property Values
Thanks all for your input on this question. I enjoy this forum and have learned a lot in the short time that I have been here and I definitely appreciate that I can post my questions here comfortably without being ridiculed for my simple questions.
The only complaint I have is that some of the tougher questions I pose seem to go unresolved.
-
Jan 21st, 2010, 01:46 PM
#25
Fanatic Member
Re: [RESOLVED] Default Property Values
 Originally Posted by wolfpackmars2
The only complaint I have is that some of the tougher questions I pose seem to go unresolved.
I've found sometimes using another board will get a response on some subjects not answered on the vb.net forum, for example if i have a question relating to Httprequests then the ASP board gets better responses. Also showing some code in the opening post tends to help with replies.
If debugging is the process of removing bugs, then programming must be the process of putting them in.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|