How to make a class method default, and use the square brackets?

  • Thread starter Thread starter Derrick
  • Start date Start date
D

Derrick

I'm writing a read/write properties file, how do I simluate the
AppSettings["myProp"] method to get/set a value?

Thanks in advance!
 
Hi Derrick,

For the get statement
System.Configuration.ConfigurationSettings.AppSettings.Get() method.
For the set method you can use the System.Xml.XmlDocument class:

// Get the config file and read it as XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sExePath + ".config");
// Loop through the nodes and find the needed node
foreach(XmlNode xmlNode in xmlDoc["configuration"]["appSettings"])
{
if(xmlNode.Attributes.GetNamedItem("key").Value == KeyName)
{
// Update value
xmlNode.Attributes.GetNamedItem
("value").Value = KeyValue;
xmlDoc.Save(sExePath + ".config");
return;
}
}
 
It's called "indexer":


class AppSettings
{
string this[string name]
{
get
{
return ...
}
}
string this[int index]
{
get
{
return ...
}
}
}


HTH,
Alexander
 
You can make this example more featured if you use some variations of
GetValue and SetValue.

public class Class1
{
private int _a;
private int _b;

public Class1()
{

}

public int a
{
get {return _a;}
set {_a = value;}
}

public int b
{
get {return _b;}
set {_b = value;}
}

public object this [string PropertyName]
{
get
{
return this.GetType().GetProperty(PropertyName).GetValue(this, null);
}
set
{
this.GetType().GetProperty(PropertyName).SetValue(this, value, null);
}
}

}
 
I think what you are asking is to implement an indexer of your class.
It will allow an object of your class to be accessed in the manner you
want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top