[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Calculate the factorial function and use Debug.Assert in C#

factorial function

The factorial of a number N is written N! and has the value 1 * 2 * 3 * ... * N. By definition, 0! = 1.

The value N! gives the number of permutations of a set of N objects. For example, if you have 5 objects, then you can arrange them in 5! = 1 * 2 * 3 * 4 * 5 = 120 different orders.

Calculating the factorial of a number N is fairly easy. Simply set a result variable equal to 1 and multiply it by the integers between 2 and N.

// Calculate N! private decimal Factorial(decimal N) { Debug.Assert(N >= 0); decimal result = 1; for (decimal i = 2; i <= N; i++) result *= i; return result; }

One thing about this code deserves special mention: the Debug.Assert statement. The Debug class is in the System.Diagnostics namespace, so the example program includes the following using statement to make using the class easier.

using System.Diagnostics;

When you run the debug version of the program, the Debug.Assert statement checks a boolean expression and throws an exception if the expression is false. Optional parameters let you specify things such as the error message the exception should include.

When you run the release version of the program, this statement is removed. It doesn't run and doesn't even take up space in the compiled program. This lets you test for errors while you are building your application, and then remove those tests to improve performance in the release build.

Debug.Assert can help you pinpoint bugs quickly without hurting performance in the release build, so I whole-heartedly recommend that you use it for sanity checks in your code. For example, you can use it to make sure function parameters make sense and that calculated results look correct.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.