What I'm trying to find out whether you can have something like underneath or not:
namespace myNamespace
{
public string myString;
}
I couldn't find anything that explained this, probably because of my terrible searching keywords. Could anyone tell me if there is a way to do this or not?
If this is possible, I may have goofed up something. Either way, I'd like to know.
I wanted to know how to do this because I want to have access to this in the whole namespace without having to go something.myString when I'm inside a different class. This was something that seemed logical in my eyes, but it's apparently not possible.
You can't declare field directly in the namespace
:
// doesn't compile
namespace myNamespace
{
public string myString; // <- syntax error
}
but you can emulate such a syntax with a help of using static
(C# 6.0+):
namespace MyLibrary
{
// put myString within a static class
public static class MyStorage
{
// let turn field into property
public static string myString {get; set;}
}
}
Then use the static class with using static
:
// please, notice "using static"
using static MyLibrary.MyStorage;
namespace myNamespace
{
public class MyClass
{
public void MyMethod()
{
myString = "abc"; // as if it has been declared in the namespace
string test = myString;
...
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments