Abder KRIMA
Abder KRIMA

Reputation: 3678

How to make constant final variables in a class like module in vb.net but in C#?

I want to make all my fixed string in a variables in a one class named Constantes whith will looks like:

class Constantes
{
    public static sealed String var1 = "variable 1";
    public static sealed String var2 = "variable 2";
}

And in an other class i do this :

class main
{
    ...
    list.add(Constantes.var1);
    list.add(Constantes.var2);
}

I khnow that in the vb.net we can do this by using modules but in c# i don't khnow how.

Upvotes: 1

Views: 2545

Answers (4)

Jcl
Jcl

Reputation: 28272

Make the class static:

public static class Constantes
{
  public static string var1 = "variable 1";
  public static string var2 = "variable 2";
}

And maybe make your members const if you want them constant (const are basically static members which you can't overwrite)

public static class Constantes
{
  public const string var1 = "variable 1";
  public const string var2 = "variable 2";
}

readonly is another possibility, but that's for runtime, so if they are truly constant, const allows for compile-time optimization (whereas readonly would only optimize in runtime)

Btw, for what I presume you are aiming, you should read on Resources, and see if that fits better

Upvotes: 4

Lews Therin
Lews Therin

Reputation: 10995

Use the const keyword, if I'm not misreading the question:

static class Constantes
{
    public const  String var1 = "variable 1";
    public const  String var2 = "variable 2";
}

Upvotes: 3

Dosper7
Dosper7

Reputation: 394

Make the class static and put the readonly keyword

public static class Constantes
{
  public static readonly string var1 = "variable 1";
  public static readonly string var2 = "variable 2";
}

Upvotes: 4

David
David

Reputation: 10708

Constants are defined using the const keyword.

class Constantes
{
    public const String var1 = "variable 1";
    public const string var2 = "variable 2";
}

note that static sealed is invalid - sealed only applied to virtual behaviour. If you want something to never be changeable (when const doesn't fit, of course), use readonly instead.

Modules are a construct of the underlying CLR, but in C#, each assembly only contains a single module, and there are no ways to define different ones. EDIT however, they are not the same VB Modules. See MSDN for more details on these differences

Upvotes: 1

Related Questions