Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass tuple results in one line

Tags:

c#

tuples

I have a method that returns logLevel and string, and I call it like this:

Tuple<LogLevel, string> levelAndMessage = SomeMethod();
logger.Log(levelAndMessage.Item1, levelAndMessage.Item2);

I would like to change it to one line (to not declare a variable because sometimes scopes collide).

It should look something like:

logger.Log(SomeMethod().ToValueTuple());

However then I get error

Argument 1: cannot convert from '(NLog.LogLevel, string)' to 'NLog.LogEventInfo' (CS1503)

How do I solve this?

like image 293
DisplayMyName Avatar asked Oct 23 '25 12:10

DisplayMyName


1 Answers

You could write an extension method for Logger:

public static class LoggerExt
{
    public static void Log(this Logger logger, (LogLevel logLevel, string message) args)
    {
        logger.Log(args.logLevel, args.message);
    }
}

Then you could call it like you wanted:

var logger = new Logger();

// ...

logger.Log(SomeMethod());

Full compilable console app example:

namespace ConsoleApp1
{
    public enum LogLevel
    {
        Low,
        Medium,
        High
    }

    public sealed class Logger
    {
        public void Log(LogLevel logLevel, string message)
        {
            // ...
        }
    }

    public static class LoggerExt
    {
        public static void Log(this Logger logger, (LogLevel logLevel, string message) args)
        {
            logger.Log(args.logLevel, args.message);
        }
    }

    class Program
    {
        public static void Main()
        {
            var logger = new Logger();

            // ...

            logger.Log(SomeMethod());
        }

        public static (LogLevel logLevel, string message) SomeMethod()
        {
            return (LogLevel.High, "Some message");
        }
    }
}

However, without knowing the full context of where you want to use this, I can't really say that this is a good idea...

(Note that this answer is using C# 7.x tuples; if you are using an earlier version then you will have to adjust the parameter types to use Tuple<> as appropriate.)

like image 78
Matthew Watson Avatar answered Oct 26 '25 01:10

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!