Tuesday, July 14, 2009

In C#, how do you declare a constant such that it can be used in a different class?

namespace abc


{


public class abcData


{


public const string str = "xyz";


}


}





I want the constant str to be accessible from another file that is referencing the "abc" namespace with "using abc;". How do I do this?

In C#, how do you declare a constant such that it can be used in a different class?
According to Object Oriented Design, you really shouldn't expose class properties directly. The task you're trying to accomplish can be done by using accessors with no Set method, ie. in this way:





namespace abc


{


public class AbcData


{


private const string str = "xyz";





public string AbcString


{


get { return str; }


}


}





}





In this way, you're hiding str, and exposing it using the Get Accessor method.
Reply:If you declare the constant as static, such as





public const static string str = "xyz";





then you should be able to reference the constant in another file by using abcData.str (if you're already "using abc;").

survey for money

No comments:

Post a Comment