Reputation: 1239
How to add a instance of class into a variable c#?
for (int i = 0; i < 8; i++)
{
var msg = new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
};
// What I need to do to acumulate msg variable into a new variable?
}
Upvotes: 0
Views: 90
Reputation: 624
You can create a list of Param
var listParam = new List<Param>();
for (int i = 0; i < 8; i++)
{
var msg = new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
};
listParam.Add(msg);
}
Upvotes: 5
Reputation: 30813
const int count = 8;
var messages = new Param[count];
for (int i = 0; i < count; i++)
{
var msg = new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
};
messages[i] = msg;
}
Upvotes: 2
Reputation: 218818
Append the object to a list that exists outside of the loop, instead of just to a variable that only exists inside the loop. For example:
var msgs = new List<Param>();
for (int i = 0; i < 8; i++)
{
msgs.Add(new Param
{
type = "text",
text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
});
}
// here you have the list of Param objects created in your loop
Upvotes: 5