Archive for September, 2007

Welcome to Math Class

Today's Subject: System.MathThe .NET math class provides you with several handy math routines you can use even if you’re not doing complex trigonometric or logarithmic functions. In this article we will take an introductory look at the non-trig, non-log, functions and how to use them in your code.

Abs

This is an old familiar command to VB Classic and BASIC programmers. It returns the absolute value of a number and it accepts SByte, Short, Integer, Long, Decimal, Single, and Double data types in its overloads. Remember it returns the same type of data that you send it. It doesn’t do conversions between numeric types like previous versions of VB and BASIC when you have Option Strict On (which you should always have on). You’ll need to handle the conversion yourself.

Also, don’t forget that you have to prefix it with Math or use “Imports System.Math” in your module or project namespace. Here’s an example of this function:

Dim NewValue As Integer = Math.Abs(OldValue)

BigMul

If you’re working with big integers this function can be quite helpful in helping you avoid overflow exceptions. Remember the product of multiplying two Int32 values is an Int32 value. If your product exceeds the upper or lower Int32 range you’ll get an exception. To avoid this situation, you can use BigMul to multiply two Int32 values and return a Int64 value. Here’s a simple example:

Dim ABigNumber As Integer = 40000000
Dim AnotherBigNumber As Integer = 40000000
Dim ABigProduct As Int64 = Math.BigMul(ABigNumber, AnotherBigNumber)

DivRem

First BigMul and now DivRem, did somebody at Microsoft not get the memo about using meaningful function names? Anyway, DivRem calculates and returns the quotient of two integers, either 32 or 64 bit, plus it also returns the remainder in an output parameter. This function is handy if you want to get both the quotient and remainder in a single swoop. Here’s an example:

Dim TestIt As Integer = 578
Dim TestToo As Integer = 75
Dim TestValue As Integer
Dim TestRemainder As Integer
TestValue = Math.DivRem(TestIt, TestToo, TestRemainder)
Debug.Print(String.Concat(TestValue, " | ", TestRemainder))

Output Value: 7 | 53

Remember to make sure that you don’t accidentally divide by zero here.

IEEERemainder

This function is sort of like DivRem except that it’s for doubles and that it returns the remainder, not the quotient (which gets dropped). Kind of an inconsistant design if you ask me. Here’s an example of this function:

Dim TestAgain As Double = 194.89482
Dim RemainderTest As Double = Math.IEEERemainder(TestAgain, Math.PI)

Output Value: 0.116075477432837

Note the use of the Pi constant value in this example.

Sign

Sign is a simple, straightforward function. It returns -1 if the target number is negative, 0 if the number is zero, and 1 if the number is positive. There are overloads that will work with any of the signed number types. Here’s an example:

Select Case Math.Sign(TestAgain)
    Case 1
        'positive number action
    Case 0
        'zero action
    Case -1
        'negative number action
End Select

Ceiling and Floor

These functions are useful with decimal and double values where you want to obtain the nearest whole number that’s either greater than (ceiling) or less than (floor) of the given number. This could be useful in a custom rounding routine. Here are some examples and the result of the operation

Dim MyValue as Double
MyValue = Math.Ceiling(194.89482)

Output Value: 195

MyValue = Math.Floor(194.89482)

Output Value: 194

MyValue = Math.Ceiling(-194.89482)

Output Value: -194

MyValue = Math.Floor(-194.89482)

Output Value: -195

Truncate

Truncate is like the old VB6/MSBASIC Fix function (this function is still in the Microsoft.VisualBasic Namespace). It simply drops the decimal portion of the target decimal or double number. Here’s the example

Dim IntValue As Integer = CInt(Math.Truncate(TestAgain))

Notice that this function also returns a double or decimal rather than an integer and this requires conversion unless you’re unwisely not using Option Strict On.

Max and Min

These functions respectively return the larger or lesser of the two numbers passed in. These functions could be quite useful for sorting routines or for random selection routines.

LowestPrice = Math.Min(NewProduct.Price, OldProduct.Price)

Pow

Pow simply raises an number to a specified power, just like the ^ operator does. I’d just use the operator myself.

Debug.Print(String.Concat(7 ^ 8))
Debug.Print(String.Concat(Math.Pow(7, 8)))

Output Value for both: 5764801

Round

I covered Round in depth in this earlier article: What You Should Know About Rounding in VB.NET

I hope this article has given you a good overview of the Math class functions. While there is some redundancy there are few hidden gems as well. As always, let me know what you think by leaving a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

1 comment September 19th, 2007

3 Quick String Tips

If Me.LastIndexOf("Cherry Limeade") = 0 ThenMy articles on using Strings in VB.NET have been rather popular and appreciated so here’s another one. This time we’ll look at 3 quick and useful tips for using Strings. These are simple but they’re often overlooked, particularly by those new to VB.NET. Hopefully these tips will help you prevent errors in your code and improve performance.

1. Watch Your String Length and Indexes

Previous versions of VB and BASIC in general used one based strings for functions. Some of the Microsoft.VisualBasic Namespace String functions, such as Mid, still are this way. However, if you’re working with the .NET string functions you must always keep in mind that you’re really dealing with a zero based character array behind the scenes. This means that any index value you use must be zero or greater and can’t be greater than or equal to the length of the string. Always check your length before performing string functions like SubString to prevent costly exceptions.

2. Nothing vs. String.Empty

Do you know the difference between a string variable equal to Nothing and one equal to an empty string? Nothing means that the variable does not have an object associated with it while String.Empty means that there is an object that is set to an empty string. Remember that String variables are always Nothing when you declare them unless you initialized them at that point. If you try to use a string variable that has a value of Nothing you will get a Null Reference Exception. I’ve seen this little bug pop up often in property routines and their associated variables.

3. LastIndexOf vs. IndexOf

A common point of confusing with these functions is with the extra parameter overloads where only part of a string is being considered. First of all, go back to tip #1, know the length of the string so that you won’t get a ArgumentOutOfRange exception. Remember that the IndexOf search moves from the start of the string to the end of the string while LastIndexOf searches from the end to the start. This would mean that the first call below would cause an exception while the second one would be OK.

Dim Test As String = "abcdefghijklmnopabcdefghijklmnop"
Dim Position As Integer
Position = Test.IndexOf("abc", 24, 10) 'throws exception
Position = Test.LastIndexOf("abc", 24, 10) 'OK 

I hope you found these ideas helpful. If you have some of your own you would like to add or if you have questions or observations about these tips, please leave a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment September 18th, 2007

Introduction to System.Enum

Enums allow you to construct better appsEnums, or enumerations, as you probably already know, allows you to create a set of logically related constant values. Using them means you can avoid hard coding numbers and you make your code more readable and maintainable because you’re using memorable and logical names for the values.

One problem that VB6 programmers often ran into was that there was no easy way to extract the matching string for a value. This typically led to clumsy conversion code and/or database tables that had to be maintained whenever the Enum changed. However, in .NET, we now have the System.Enum object to take care of this situation and more. In this article, we will take a look at some of the useful functions in this object.

GetName

The first function we’ll look at is GetName. As you might suspect, this returns the string associated with an Enum value. Here’s what the code looks like, first our example Enum declaration, followed by the GetName call.

Public Enum EmailTypes
    Introduction
    Sales_Flyer
    Thank_You
    Important_Notice
    Holiday_Greetings
    Other
End Enum

..............

EnumValue = System.Enum.GetName(GetType(EmailTypes), EmailTypes.ThankYou).Replace("_", " ")

In this case our return value would be “Thank_You”. I used the underscore in the enum name to make it easy to replace it with a space for display purposes. You can’t have a variable name, or an Enum member name, with a space.

GetNames

OK, that’s one value. What if you wanted them all so that you could add them to a combo or list box control? That’s what GetNames is for. Here’s the code, using our same example Enum above.

lstEmailType.Items.AddRange([Enum].GetNames(GetType(EmailTypes)))
.
.
.

Of course, this doesn’t remove the underscore from the strings but this would be easy enough to add if you needed it with a simple loop. Also note that we used “[Enum]” in the code above rather than System.Enum. Coding it in the square brackets shows that we’re using the object rather than the statement of the same name.

GetValues

Sometimes you might want to return all of the values in an Enum at once. For this, you would use the GetValues function as seen here:

Dim EmailValues As Array
EmailValues = [Enum].GetValues(GetType(EmailTypes))
For Each EmailValue As Integer In EmailValues
    'more code goes here
Next

This function makes it easier for us to iterate through the values in an enum.

IsDefined

This function is used to determine if a string name or a numeric value is defined in the Enum. For example…

If [Enum].IsDefined(GetType(EmailTypes), "Thank_You") Then

............

If [Enum].IsDefined(GetType(EmailTypes), 9) Then

…the first If would evaluate to True since we do have an Enum named “Thank_You” in our example. The second would return False because we don’t have that value in our example Enum.

That’s all for this tutorial. There are a few more methods in the Enum object that you might want to explore on your own that I didn’t cover here. Let me know if you have any questions or observations about this article by leaving me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

1 comment September 17th, 2007

The VB.NET Salary Gap

What are they putting in your wallet?Have you ever wondered what the salary difference is between a VB.NET and a C#, C++ or Java job? I did a little research on this tonight, courtesy of Indeed.com, the job listing aggregation site I have in my sidebar. What I found really wasn’t all that surprising but it was interesting none the less.

The Gap

We’ll start off with what I found: A VB.NET programmer is worth roughly $6000 less a year than a comparable C#, C++, and Java programmer. This gap holds true across all job levels, entry level, mid-level, and senior. Here are screen shots of the aggregate numbers:

Indeed.com VB.NET Jobs Aggregate Salary

Indeed.com C# Jobs Aggregate Salary

So, Should You, and I, Learn C#?

Over all, I think this salary gap is a perception thing. The management who sets the salary levels probably is comfortable with looking at VB code and thinks because it’s readable it must be easy. Likewise, they see a few curly braces and semi-colons in C#/C++/Java and think, “Oh, this must be hard.” Ultimately, it’s our job as VB programmers to show them that our skills and ability are on par with the others. That is certainly one of the goals I have in minds with this site.

Should you switch to C#? Well, that’s really a personal decision, but I think that there is great value in being comfortable in coding in either VB.NET or C# within the .NET framework. At the core, they really aren’t all that different. Outside the Framework, it is always helpful to your career and general programming skill to know multiple languages. Who knows when a Java or C++ algorithm might be helpful to your VB.NET application? Knowing how to translate it would be quite helpful to you.

My approach is going to be to always be in learning mode. If I’m learning something new, whether it’s in VB or C# or another language, I think I’m headed in the right direction. What’s you’re take on this? Is the potential for a $6k a year worth switching exclusively to C#? Leave me a comment and let me know.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

22 comments September 17th, 2007

How to be a Benevolent Dictator

A Bad Boss-tator in actionThe software development world is filled with bosses who treat their words as if they were edicts from the throne. This works, sometimes, but it is often at the expense of team morale. Without the prevalence of bosses like this, we wouldn’t knowingly laugh at Dilbert’s “pointy haired boss” or Office Space’s Bill Lumbergh. However, a pure majority rules scenario also encounters problems when a tough, contentious, decision has to be made. Most often the ‘decision’ in this case is no decision at all and the problem goes unsolved. Between these two extremes is where the Benevolent Dictator comes into play.

Leading Without Leading

The first idea is to allow the team to make the majority of their decisions as a team. You don’t have to jump into every difference of opinion with your words from on high. Instead, listen, find points of agreement and bring them up, and help the team to reach a consensus. This gives the team a feeling of group achievement and comradery that would be missing if you forced the issue.

You shouldn’t make important decisions without some input from the team, either in the form of a vote or a group discussion. Too often, managers will make decisions on things like which version control system or coding standard is to be used and barely consult the team or even not consult them at all. By allowing participation the benevolent dictator insures popular support for a decision.
However, you should not simply abdicate your role as leader to someone else. I have seen some managers, particularly ones with lacking technical or interpersonal skills, allow a more forceful person to become the defacto leader. This can undermine your ability to lead a team when your leadership is needed. And there will always be time when it is needed.

But You May Need To Impose a Decision

One common failing in self-lead teams is the inability to reach a decision, particularly on tough choices. As one team member I used to work with was fond of saying, “That’s a non-issue”. Unfortunately, often it was an issue and it came back to bite us later. The benevolent dictator’s role is to identify those areas where a hard decision is needed. If the team can’t reach a consensus by being guided toward it, then it will become time to impose a choice to break the deadlock. Sometimes just the implication that this will happen will be enough to have the team develop a consensus.

Sometimes a decision might be so polarizing, like those that often come up when discussion coding standards, that putting it up for vote or organized group discussion might damage the team’s ability to function. In that case, it may make sense for you to impose a solution or compromise rather than having the team at each other’s throats. They might not like you for a while but, with any luck, the team should be intact. The key thing here is to use your power very judiciously and not arbitrarily and to give a good, solid, explanation for your decision.

The Goal: An Effective Team

The goal of anything a benevolent dictator does should be to build an effective team, a team that develops software that solves the problem at hand. When your decisions, or lack of decision, fails to work toward that goal, your leadership of the team has become ineffective. If your interpersonal or technical skills are holding you back, take steps to improve them. Likewise, if you find yourself bullying your team, learn to keep this tendency in check. It’s all about seeking the right balance to achieve your goal, a high performance team.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment September 16th, 2007

Next Posts Previous Posts


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives