-2

I am trying to see the output as "200". I have about 400 variable names with different settings from a flat file and I need to load the configuration but having a hard time casting the type to set the settings.

    private double test1 = 100;

    private void button1_Click(object sender, EventArgs e) {

        double testNewType = (double)test1;

        testNewType = 200;

        Debug.Print(test1.ToString());
    }
XK8ER
  • 770
  • 1
  • 10
  • 25
  • 1
    double isn't a reference type, so `testNewType` is just gonna be a copy of the content. – Jack T. Spades Jun 11 '21 at 00:09
  • so to load settings from text file the only way is to type 400 if statements and check name of double variable and set its value? – XK8ER Jun 11 '21 at 00:14
  • Does this answer your question? [Get reference of value type C#](https://stackoverflow.com/questions/12265945/get-reference-of-value-type-c-sharp) and [Store a reference to a value type?](https://stackoverflow.com/questions/2256048/store-a-reference-to-a-value-type) –  Jun 11 '21 at 02:45

2 Answers2

0

You are printing test1, not testNewType

Debug.Print(test1.ToString());

Debug.Print(testNewType.ToString());

If you are trying to pass by reference, I’m not sure C# can do that with doubles, and definitely not when you cast it.

thshea
  • 1,048
  • 6
  • 18
  • so to load settings from text file the only way is to type 400 if statements and check name of double variable and set its value? – XK8ER Jun 11 '21 at 00:14
  • You could use reflection as in the other comment. You could also create a hash table (or dictionary, not sure what it’s called in c#) with the variable name as an index if that makes more sense for you. Then you can assign values using the name in the text file and reference them later with the same name. – thshea Jun 11 '21 at 00:20
0

If you want to set fields you can do it with reflection:

/*
Get type, you can also use
var type = this.GetType();
*/
var type = typeof(YourClassNameWithFields);

/*
Add BindingFlags.DeclaredOnly 
if you only want to set declared fields in current class (ignoring inheritance)
*/
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

foreach(var field in fields){
  //targetObject is Object to which you want to set value, can be this
  field.SetValue(targetObject, newValue);
}

Also you can use dynamic type, just like this:

dynamic obj = yourObject;
obj.fieldName = value;
Alex
  • 526
  • 2
  • 8