Niranjan
Niranjan

Reputation: 587

Read data from app.config and use it across multiple classes in c#

Hi I am reading the values from app.config. I have different sections as below.

<TEST>
    <add key="key" value="value1" />
  </TEST>

  <DEV>
  <add key="key" value="value1" />
  </DEV>

I am accessing these values in my class files as below.

protected static NameValueCollection keyvalue = ConfigurationManager.GetSection("DEV") as NameValueCollection;

If I want to read values from 5 different classes then I have to write above code in all 5 classes and If I want to change DEV to TEST then I need to change in 5 places. Is there any way I can simplify this steps? Or Is there any best practices I can follow up? Any help would be greatly appreciated. Thank you.

Upvotes: 0

Views: 313

Answers (2)

CodeConstruct
CodeConstruct

Reputation: 414

Hi I would suggest following this link which tells how to manage debug and release mode in C#.C# Debug & Release mode

Upvotes: 0

Dennis Vanhout
Dennis Vanhout

Reputation: 103

Access Modifiers

make a public static string containing the value you want.

Then just refer to that instead of directly inserting the value.

And whenever you want to change it, you just have to change the value of the static in that one place.

public static string Section = "DEV";

and then you can just insert this, so you only have to change the value of Section when you want to switch.

protected static NameValueCollection keyvalue = ConfigurationManager.GetSection(Section) as NameValueCollection;

Upvotes: 1

Related Questions