Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a named tuple with only one field

Tags:

c#

I wrote a function in c# which initially returned a named tuple. But now, I only need one field of this tuple and I would like to keep the name because it helps me to understand my code.

private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
        // do something
        return (true, false);
    }

This function compile. But It's the following function that I want

private static (bool informationAboutTheExecution) doSomething() {
        // do something
        return (true);
    }

the error messages:

Tuple must containt at least two elements

cannot implcitly convvert type 'bool' to '(informationAboutTheExecution,?)

Has somebody a solution to keep the name of the returned value?

like image 659
Pierre-olivier Gendraud Avatar asked Apr 08 '21 13:04

Pierre-olivier Gendraud


People also ask

What is the point of NamedTuple?

attr . Python's namedtuple was created to improve code readability by providing a way to access values using descriptive field names instead of integer indices, which most of the time don't provide any context on what the values are. This feature also makes the code cleaner and more maintainable.

How do I access the NamedTuple field?

The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

Are named tuples mutable?

Named Tuple Python's tuple is a simple data structure for grouping objects with different types. Its defining feature is being immutable.

How do you write a tuple in Python?

Using namedtuple to Write Pythonic Code Python’s namedtuple () is a factory function available in collections. It allows you to create tuple subclasses with named fields. You can access the values in a given named tuple using the dot notation and the field names, like in obj.attr.

How do I change the value of a named tuple field?

Note: In named tuples, you can use ._replace () to update the value of a given field, but that method creates and returns a new named tuple instance instead of updating the underlying instance in place.

Why would you use a named TUPLE?

Anyone reading your code can see and understand that. Your new implementation of pen has two additional lines of code. That’s a small amount of work that produces a big win in terms of readability and maintainability. Another situation in which you can use a named tuple is when you need to return multiple values from a given function.

What is the candidate name of a tuple?

The candidate name is a duplicate of another tuple field name, either explicit or implicit. In those cases you either explicitly specify the name of a field or access a field by its default name. The default names of tuple fields are Item1, Item2, Item3 and so on.


Video Answer


2 Answers

I just want to add another option, althought he out is the easiest workaround and Marc explained already why it's not possible. I would simply create a class for it:

public class ExecutionResult
{
    public bool InformationAboutTheExecution { get; set; }
}

private static ExecutionResult DoSomething()
{
    // do something
    return new ExecutionResult{ InformationAboutTheExecution = true };
}

The class can be extended easily and you could also ensure that it's never null and can be created with factory methods like these for example:

public class SuccessfulExecution: ExecutionResult
{
    public static ExecutionResult Create() => new ExecutionResult{ InformationAboutTheExecution = true };
}
public class FailedExecution : ExecutionResult
{
    public static ExecutionResult Create() => new ExecutionResult { InformationAboutTheExecution = false };
}

Now you can write code like this:

private static ExecutionResult DoSomething()
{
    // do something
    return SuccessfulExecution.Create();
}

and in case of an error(for example) you can add a ErrorMesage property:

private static ExecutionResult DoSomething()
{
    try
    {
        // do something
        return SuccessfulExecution.Create();
    }
    catch(Exception ex)
    {
        // build your error-message here and log it also
        return FailedExecution.Create(errorMessage);
    }
}
like image 98
Tim Schmelter Avatar answered Oct 16 '22 09:10

Tim Schmelter


You cannot, basically. You can return a ValueTuple<bool>, but that doesn't have names. You can't add [return:TupleElementNamesAttribute] manually, as the compiler explicitly does not let you (CS8138). You could just return bool. You can do the following, but it isn't any more helpful than just returning bool:

    private static ValueTuple<bool> doSomething()
        => new ValueTuple<bool>(true);

Part of the problem is that ({some expression}) is already a valid expression before value-tuple syntax was introduced, which is why

    private static ValueTuple<bool> doSomething()
        => (true);

is not allowed.

like image 7
Marc Gravell Avatar answered Oct 16 '22 08:10

Marc Gravell