Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const String From Settings

I would like to set a const string from Settings.

In case I would like to change in the future the program language, it is quite easy; Just have to modify the appropriate settings!

When trying this:

private const string constString =   
              "-&" + Properties.Settings.Default.constStringText;  

I get this error:

The property or indexer 'Properties.Settings.Default'  
cannot be used in this context because it lacks the get accessor.  

Any idea?

like image 217
user3165438 Avatar asked Oct 20 '25 14:10

user3165438


2 Answers

Since you intend to use this as the default value for an optional method argument, that is:

public void Foo(string something = constString)
{
    //do something
}

This constString must be a compile-time constant. From the MSDN page for "Named and Optional Arguments":

A default value must be one of the following types of expressions:

  • a constant expression;

  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

  • an expression of the form default(ValType), where ValType is a value type.

As such, there really is no way to read a value from a configuration file at runtime then use it for an optional argument.

One workaround would be to instead declare your constString as a readonly field:

private readonly string constString =   
              "-&" + Properties.Settings.Default.constStringText; 

Then make your optional argument required and create a wrapping overload for your method that doesn't take that parameter. That overload in turn calls the old method with the default value resolved at runtime:

public void Foo(string something) //no longer optional
{
    //do something
}

public void Foo()
{
    Foo(constString); //calls the other overload with the default value
}
like image 174
Chris Sinclair Avatar answered Oct 22 '25 04:10

Chris Sinclair


This error is in 99% of cases related to a wrong namespace. You've probably generated some class in which you are using Properties.Settings.Default

Solution: check namespace in that class file. It must be the same as the name of the tag in App.config (Web.config) where that particular setting is stored.

like image 30
Ognjen Stanić Avatar answered Oct 22 '25 04:10

Ognjen Stanić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!