-1

I have some variables and there results which are going into database.

For example

        float[] qty1;
        Quote quote = new Quote();
        quote.qty1 = qty1[0];
        quote.qty2 = qty1[1];
        quote.qty3 = qty1[2];
        quote.qty4 = qty1[3];

I try to make this process more dynamic

           for (int i = 0; i <= 3; i++)
            {
            
            quote.qtyi = qty1[i];
            }

please help me how i can use quote.qtyi and value of i, so it will read quote.qty1, quote.qty2, quote.qty3, quote.qty4

2
  • 2
    maybe Quote.qtyx should also be an array, as qtyx is? That would be the best solutuon Commented Nov 18, 2021 at 17:49
  • @HimBromBeere Yup, though I suspect Quote may be a DB entity given the first sentence. Commented Nov 18, 2021 at 17:51

1 Answer 1

-1

Use reflection:

for (int i = 0; i <= 3; i++)
        {
        
        quote.GetType().GetProperty("qty"+i).SetValue(quote,qt1[i]);

        }

quote.getType().getProperty("qty"+i) -> Gets the property called "qty"+i from the object "quote".

.setValue(quote,qt1[i]) -> sets the value "qt1[i]" to the property (if she exists) of the object "quote".

My first answer had TYPOS, now it's compilable

Sign up to request clarification or add additional context in comments.

3 Comments

Code-only answers are particularly unhelpful. Explain what you did and why, also list potential issues (e.g. performance of using reflection)
in particula when they don't even compile
Already edited, had some typos now it should work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.