Home > Net >  How to add a instance of class into a variable c#?
How to add a instance of class into a variable c#?

Time:06-28

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?
    
}

CodePudding user response:

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

CodePudding user response:

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);
    
}

CodePudding user response:

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;
}
  • Related