Jax-p
Jax-p

Reputation: 8531

How to share constants in c#

I would like to store static variable in single class and use it in different classes.
What is the best practice in C#?


JavaScript example.
Just for example. I am looking for something like this:

I have single file MyStaticDataObject.js with one or more static variables.

const MyStaticDataObject = {
   someKey: someValue,
   anotherKey: anotherValue,
   //...
}
export { MyStaticDataObject };

and I can use them in any other file:

import { MyStaticDataObject } from "./MyStaticDataObject.js";

// ... somewhere in code
console.log(`Value of someKey:`, MyStaticDataObject["someKey"]);

Upvotes: 1

Views: 1279

Answers (2)

Mr. Squirrel.Downy
Mr. Squirrel.Downy

Reputation: 1167

Maybe late.
But this is a better way - if you need use these constants value frequently.

  1. Declare a class with some constants.
public class ConstantsClass
{
    public const string ConstName1 = "ConstValue1";
    public const string ConstName2 = "ConstValue2";
    public const string ConstName3 = "ConstValue3";
}
  1. Using this class in static in code file you want. (C# 6.0 feature)
using static ConstantsClass;

namespace YourNamespace
{...
  1. Use the constanst in the way same as it declared in local.
    CallMethod(ConstName1);

Upvotes: 1

Vishwa
Vishwa

Reputation: 195

namespace nm1 {
internal class MyStaticDataObject {
    public const string Key1 = "Value1";
    public const string Key2 = "Value2";
    }
}

In other classes (outside the namespace), reference the namespace using nm1; and use it. Otherwise they can be used directly without the using

using nm1;
internal class TestClass
{
    private string Key1 = MyStaticDataObject.Key1;
}

Upvotes: 3

Related Questions