Source code macros in VB.NET

  • Thread starter Thread starter Chris Edgington
  • Start date Start date
C

Chris Edgington

I'm a C/C++ programmer diving into VB.NET. Is there a
VB.NET equivalent to a C/C++ #define macro? For example, I
have 15 variables that I need to do the same thing to ....
in C, I'd do the following:

#define VALIDATE_AND_INIT(zMember, zNew) \
if (zNew == NULL) \
strcpy(zMember, ""); \
else \
strcpy(zMember, zNew);

Then in my code I could go:

VALIDATE_AND_INIT(FirstName, NewFirstName);
VALIDATE_AND_INIT(LastName, NewLastName);
....

Thereby making a large block of repeated code much more
manageable and easier to read and understand.

Does VB.NET provide such a mechanism?

Thanks,
-Chris
 
Chris,
VB.NET does not support #define macros!

What I would do is define a sub, which is also what I would do in C++, as it
is more type safe!

Private Sub ValidateAndInit(ByRef zMember As String, ByVal zNew As
String)
If zNew Is Nothing Then
zMember = String.Empty
Else
zMember = ZNew
End If
End Sub

ValidateAndInit(FirstName, NewFirstName)
ValidateAndInit(LastName, NewLastName)

Because the function is so short there is a good chance that it will be
in-lined by the JIT compiler at runtime, so I don't have a concern with
introducing a new function. Also, because it is a function I can overload
it.

Private Sub ValidateAndInit(ByRef zMember As Integer, ByVal zNew As
Object)
If zNew Is Nothing Then
zMember = 0
Else
zMember = CInt(ZNew)
End If
End Sub

Private Sub ValidateAndInit(ByRef zMember As Date, ByVal zNew As Object)
...

ValidateAndInit(Age, NewAge)
ValidateAndInit(Birthdate, NewBirthdate)

Note on the ValidateAndInit for Date & Integer, I defined zNew as Object
under the assumption they were coming from either controls (strings) or a
database where System.DBNull may be a value. You should define zNew as
appropriate for your use!

Alternatively I would define a function, instead of a Sub, however then
overloading gets trickier. A sub with a ByRef for the member is IMHO the
cleaner solution. NOTE: Because I am changing the caller's member field,
ByRef for zMember is needed.

Hope this helps
Jay
 
Thanks.

I noticed you set an empty string with String.Empty. Is
this the same as using ""?

Thanks,
-Chris
 
Chris,
Yes. String.Empty is a Shared Readonly field that contains the value "", so
yes they are equivalent. Shared Readonly fields are very similar to
constants.

I know of no real advantage of using String.Empty over "" for strings.
However for other classes, such as EventArgs, it is better to use
EventArgs.Empty over creating a new EventArgs object. As you save creating
an object that will later need to be garbage collection.

Strings are special in that String.Empty will be interned (folded) to the
exact same object as the "" literal, hence no real advantage.

Note this is not to say that you cannot create an empty string that is not
String.Empty ;-)

Hope this helps
Jay
 
Back
Top