Friday, October 1, 2010

Global Constants in ASP.NET

Problem
I'm trying to emulate classic ASP constant in ASP.NET. There are a few possibilities, but I find this to be the neatest.

Answer
Create a CLASS file (example: globalConstants.vb) into your project:

Public Class globalConstants
Public Const prsHelloString As String = "Hello"
Public Const priOne As Integer = 1

Public Shared Function fnoReturnNothing() As Object
Return Nothing
End Function

Public Shared Function fnsReturnEmptyString() As String
Return ""
End Function
End Class

Now, in your default.apsx files, you just need to:

Imports globalConstants
Partial Class _default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
if  globalConstants.prsHelloString = "Hello" then
'Do Nothing
end if
End Sub
End Class

You will notice that you DO NOT need to create an instance of globalConstants. No need to Dim voConsts as NEW globalConstants.  This is pretty neat.  This also works for the functions. If your class does not need to store variables, this is a great method.

No comments:

Post a Comment