Search code examples
c#unity-game-enginenetmq

How to assign a variable with .ConvertToString() method in C# to parse the message?


I am looking to learn how to assign a name to the newly converted string and then parse that string based on

string[] separatingStrings = { ",", "<<", ">>" };
string[] messages = message.Split(separatingStrings);
Console.WriteLine($"{messages.Length} substrings in text:");

below contains the var message converted to a string.

What is the name of the string so I can parse it and output it into unity debug.log?

private void ReceiveMessageLoop()
{
    while (true)
    {
        var message = new NetMQMessage();
        if (!_socket.TryReceiveMultipartMessage(MessageCheckRate, ref message, 2)) continue;

        _messageSubject.OnNext(message);
        Console.WriteLine($"0:{message[0].ConvertToString()} 1:{message[1].ConvertToString()}");
         //Console.WriteLine(message);       
    }
}

Solution

  • You can't declare a variable in a string interpolation expression.

    Console.WriteLine($"{string bar = "hello"}"); // This gives error CS1525: Invalid expression term 'string'
    

    So instead, declare it outside the string interpolation, and you can assign it in the interpolation expression with an assignment expression.

    string bar;
    Console.WriteLine($"{bar = "hello"}"); // This is OK
    Console.WriteLine(bar);
    

    Your specific example:

    string msg0, msg1;
    Console.WriteLine($"0:{msg0 = message[0].ConvertToString()} 1:{msg1 = message[1].ConvertToString()}");
    Console.WriteLine(msg0);
    Console.WriteLine(msg1);
    

    Bonus tip: You can, however, use an out variable declaration in an interpolation expression. The scope is the same as the line (not somehow local to the interpolation expression). e.g.:

    class Program
    {
        static string Test(out string x, string y) {
            return x = y;
        }
    
        static void Main(string[] args)
        {
            Console.WriteLine($"{Test(out string bar, "Hello")}");
            Console.WriteLine(bar);
        }
    }