Is it possible to use a constant namespace wide?  
Author Message
Marci Weinberger





PostPosted: Visual C# IDE, Is it possible to use a constant namespace wide? Top

Hi All,

C# only allows for the defining of a constant inside a class. Is it possible to have other classes use that constant Here is an expample

// Assume in file MyFile1.cs
namespace MyNameSpace
{
// Assume in file MyFile1.cs
class MyClassToUse
{
public void WriteMe()
{
String strHi;

strHi = MYCONST_TOUSE1;
}
}
}

// Assume in file MyFile2.cs
namespace MyNameSpace
{
class MyClassToDefine
{
public const MYCONST_TOUSE1 = "Hi!";
}
}

The above code produces a compiler error, because VS05 only knows about the constant in MyFile2.cs. Is it possible to use a constant namespace wide

Thanks in advance,

Marci Weinberger


Visual C#11  
 
 
Brendan Grant





PostPosted: Visual C# IDE, Is it possible to use a constant namespace wide? Top

You can use it... only need to prefix it with the class that it is located in, so your WriteMe() method would become:

class MyClassToUse
{
public void WriteMe()
{
String strHi;

strHi = MyClassToDefine.MYCONST_TOUSE1;
}
}

Also, don't forget to define a type (string ) for the const itself.



 
 
Marci Weinberger





PostPosted: Visual C# IDE, Is it possible to use a constant namespace wide? Top

Hi Again Brendan,

Thanks for coming to my aid again. :-) I found out that you have to literally use the class name and not an instantiation of the class. You are right. In my sample I forgot to add 'String' to my constant. I checked the real code and I didn't forget there. Oh well, so much for on the fly typing.

Marci

 
 
Brendan Grant





PostPosted: Visual C# IDE, Is it possible to use a constant namespace wide? Top

Glad I could be of help.

To expand on what you said... nested classes, and static and constant fields, properties and methods that are public and are part of another class have to be prefixed with that class when using them... even if they are static and creating an instance is not required.

It is also worth noting that Enums are pretty much the same way, a radical departure for many with deep roots in C/C++ where just the value name could be used, instead of the type name and the value name.