Steven_M

I am new to C# coming from a Java background. Is this the best way to handle properties

public sealed class Properties {

private static readonly Properties singleton = new Properties();

private static Hashtable values = null;

static Properties() {

values = new Hashtable();

try {

LoadProperties(values);

} catch (Exception) {

}

}

private static void LoadProperties(Hashtable table) {

//Load properties from any external source such as xml file, database, etc...

}

public static Properties Singleton {

get {

return singleton;

}

}

public String getProperty(String name) {

if (values.ContainsKey(name)) {

return (String)values[name];

} else {

return null;

}

}

//list of valid lookup values

public const String PROXY_HOST = "PROXY_HOST";

public const String PROXY_PORT = "PROXY_PORT";

...

}

Then code such as the following is used to access it:

String proxyHost = Properties.Singleton.getProperty(Properties.PROXY_HOST);

I want the class to be flexible enough to work with files and/or databases as the source. I think the singleton pattern part of the code is correct. Just curious if there is a better way to do it in C#...



Re: Visual C# General Pattern for properties

OmegaMan

This code snippet can be found on my blog entitled Using the Indexer on a C# Class for Easier Data Access, and there is a better way. By overloading the this operator, one can have the class access important information. Note the below snippet does not do error checking and the static function is there for example purposes:

Code Snippet

public class ShowConcepts
{
// Only here for example usage
public static void Usage()
{
ShowConcepts sc = new ShowConcepts();

sc.Add(8675309, "Jenny");

sc[90125] = "Yes";

Console.WriteLine(sc[8675309]); // Prints Jenny

}

Dictionary<int, string> _myData = new Dictionary<int,string>();

// The ability to add a value via an add method.
public void Add(int key, string value)
{
_myData.Add(key, value);

}

// Index the data here
public string this[int key]
{
get
{
return _myData[key];
}

set
{
_myData[key] = value;
}
}

}






Re: Visual C# General Pattern for properties

Steven_M

That would allow me to get rid of the getProperty() function...

I am more concerned with the pattern as it applies to something like reading properties from a database into a singleton object for all classes to share.





Re: Visual C# General Pattern for properties

James Curran

Here's how I would do it.



public static class Properties
{
static readonly StringDictionary values;
static Properties()
{
values = new StringDictionary();
try
{
LoadProperties(values);
}
catch (Exception)
{ }
}

static public StringDictionary Values
{
get
{
return values;
}
}

static void LoadProperties(StringDictionary sd)
{
sd["A"] = "Hello, World!";
}
}

String proxyHost = Properties.Values[Properties.PROXY_HOST];