Reputation: 69
I was wondering how to get a variable equivalent from another .cs file with "using" statement. Like
using (namespace here)
Output(A, 8);
and the file with (namespace here) would have
A = 3
would I be able to directly refer to the variable, or would I need to locate it some other way?
Upvotes: 1
Views: 9729
Reputation: 700412
You can't dynamically change the scope of a code like that. What an identifier is, is determined at compile time, so you can't change what it means at runtime.
Make a class or an interface that specifies what it is that you want to use from the different files, then inherit the class or implement the interface to make different implementations in different files. When you use one of the implementations you get the values from that file.
Example:
public interface ICommon {
int A { get; }
}
public class File1 : ICommon {
public int A { get { return 42; } }
}
public class File2 : ICommon {
private int _value = 1;
public int A { get { return _value; } }
}
Now you can use different objects:
ICommon x;
if (something) {
x = new File1();
} else {
x = new File2();
}
Output(x.A, 8);
Upvotes: 1
Reputation: 203835
If you just want to define a bunch of constant values in one location that can be used elsewhere this is the standard pattern you would follow:
namespace MyNameSpace
{
public static class Constants
{
public const int MyFavoriteNumber = 3;
}
}
Then somewhere else you can have:
using MyNameSpace;
namespace MyOtherNameSpace
{
public class MyClass
{
public void Method()
{
Console.WriteLine(Constants.MyFavoriteNumber);
}
}
}
Upvotes: 4
Reputation: 152566
.CS files contains classes, not variables. If the .CS file contains a class that has a static property A you would just reference that static property:
Output(ClassName.A, 8);
Otherwise you need to provide more context as to what you have and what you're trying to do.
Upvotes: 0