Monday, March 26, 2012

Set Default value for a Property in a user defined class

Hello,
I have created a class in vb .net and would like to add a property tothis class with a default value. The purpose of this would bethat if the user didn't supply a value for the property (or evenreference the property) it would contain the default value. Forexample here is what I have tried:
Public Shared MultipleResults As Boolean = False
My pages don't work properly as the property doesn't seem to be set to False.
Thanks in advance,
Paul Liadis
Penn State University
What do you mean by "pages don't work properly"? Do they crash or are you just not getting the results you expect?
An uninitialized Boolean will return False (which is ambiguous, of course). For example:
Class Test
Public Shared MultipleResults As Boolean = False
Public Shared MultipleResultsUnInit As Boolean
End Class
Sub Button1_Click(sender As Object, e As EventArgs)
Dim t As New Test
Response.Write("<br>Value = " & t.MultipleResults)
Response.Write("<br>Value = " & t.MultipleResultsUnInit)
End Sub

When I run this, I get False for both properties.
Are you perhaps running into the issue that the property value is not being persisted across postbacks?


Sorry about the vague statement "doesn't work". The pages do notcrash. They give results that I did not expect. Here is avery small version of the example you gave, with slight midifications:
Class Test
Public Shared globalCustomColumnWidths As Boolean = False
' many other subroutines and such here
shared sub ASubroutine()
If globalCustomColumnWidths = False Then
TableCellObj.Width = Unit.Percentage(25)
Else
TableCellObj.Width = Unit.Percentage(globalWidthArray(0))
End If
end sub
End Class
What I would like to happen is that when I call my test class, I would like for globalCustomerColumnWidths to
evaluate to false, even if I don't set it to anything. This doesn't seem to be happening. Any thoughts? Also,
what did you mean by "An uninitialized Boolean will return False (which is ambiguous, of course)."?
Thanks for the response.



Sorry, I'm not understanding the relationship between globalCustomColumnWidths and MultipleResults. (?)
>"ambiguous, of course"
That if an uninitialized Boolean returns false, you don't know whether it's uninitialized or has been explicitly set to false.

0 comments:

Post a Comment