C# Parallel Computing: Parallel.For-loop

The C# For-loop in Parallel computing looks easy. Something I will need to keep in mind when doing calculations. 😉

Here is an example in .NET 4.0:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
 class Program
 {
  static void Main(string[] args)
  {
   Parallel.For(0, 2500,
     delegate(int i)
     {
      // Do some work here
      Console.WriteLine(i);
     }
    );
   Console.ReadLine();
  }
 }
}

More information about Parallel computing in C#:

Have fun!

Advertisements

Variable-length parameters in C#

Sometimes you need to call a method with one default parameter and one extra parameter. The next moment you want to call that same method with its default parameter and two or more extra parameters. In other words, you want variable-length parameters.

In Java this can be done by using … inside the parameters(/arguments) list of a method.
In C# you have several options, depending on your logic.

One choice, which will in most cases not work because of your logic, is to use an optional parameter which can be set to null (or a default value). It requires you to check if the number2 variable is null or empty every time:

public void MyMethod(int number1, int? number2 = null)
 {
 //...
 }

 

You can also choose to use method overloading but instead of writing extra code you can use the params keyword (if it fits your logic).

This code below from this simple Console Application shows some basic usage of the params keyword. One main class to call the methods and one class where the methods were implemented:

using System;

namespace VariableParamsTest
{
 class Program
 {
 static void Main(string[] args)
 {
 MyClass test = new MyClass();

 test.DoSomething(1, 2, 3);
 test.DoSomething(9, 8, 7, 6, 5, 4, 3, 2, 1);

 Console.WriteLine();

 test.DoSomethingElse(new int[] { 1, 3, 5 }, new string[] { "hello", "hi", "bonjour", "hallo" });

 Console.WriteLine();

 test.DoSomethingDifferent("monkey", 42, new double[] { 1.0, 1.1, 1.5, 1.6 });

 Console.ReadLine();
 }
 }
}
using System;
using System.Reflection;

namespace VariableParamsTest
{
 public class MyClass
 {
 public void DoSomething(params int[] numbers)
 {
 foreach (int i in numbers)
 Console.WriteLine("parameter: " + i);
 }

 public void DoSomethingElse(params object[] things)
 {
 foreach (object thing in things)
 if (thing is Array)
 foreach (object o in (Array)thing)
 Console.WriteLine("parameter: " + o.ToString());
 }

 public void DoSomethingDifferent(string word, int number, params double[] numbers)
 {
 foreach (object par in MethodBase.GetCurrentMethod().GetParameters())
 Console.WriteLine("parameter type: " + par.ToString());
 }
 }
}

 

Pretty easy, have fun testing it out. 😉

More info about params can be found on MSDN.