Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in C#

I want to use some global variables in my program. Do we have anything which could help directly define global variables as we have #define in C++.

For Eg: Say I have the below mentioned global variables in C++:

#define CROSSOVER_RATE            0.7
#define MUTATION_RATE             0.001
#define POP_SIZE                  100        
#define CHROMO_LENGTH             300
#define GENE_LENGTH               4
#define MAX_ALLOWABLE_GENERATIONS   400

I wish to define these in my C# program as global variables only. Please let me know how can I do it?

like image 819
user1277070 Avatar asked Apr 19 '12 22:04

user1277070


1 Answers

You can define them inside a class:

public static class Constants {
  public const double CrossoverRate = 0.7;
  ...
}

Use them like this: Constants.CrossoverRate.

But I'd only do that if they were really constant, like PI. For parameters that can change, I'd prefer using a class with instance-level values. I think you'll want this kind of flexibility to tune your genetic algorithm, or to use more than one parameter-set at once. This is one way to do it (immutable class):

public class GeneticAlgorithmParameters {

  public double CrossoverRate { get; private set; }
  ...

  public GenericAlgorithmParameters(double crossoverRate, ... others) {
    CrossoverRate = crossoverRate;
    ...
  }

}

Now you pass an instance of GeneticAlgorithmParameters to your GeneticAlgorithm class constructor.

like image 135
Jordão Avatar answered Sep 18 '22 18:09

Jordão