Reputation: 8531
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
Reputation: 1167
Maybe late.
But this is a better way - if you need use these constants value frequently.
public class ConstantsClass
{
public const string ConstName1 = "ConstValue1";
public const string ConstName2 = "ConstValue2";
public const string ConstName3 = "ConstValue3";
}
using static ConstantsClass;
namespace YourNamespace
{...
CallMethod(ConstName1);
Upvotes: 1
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