Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning two strings in a function in C# [duplicate]

Tags:

c#

return

Consider:

protected string Active_Frozen(string text, string color)
{
    connection();
    string query = "SELECT CustomerInfo FROM ActiveSubscription WHERE UserName=@UserName";

    SqlCommand cmd = new SqlCommand(query, conn);

    if(query=="true")
    {
        text = "Active";
        color = "Green";
    }
    else
    {
        text = "Frozen";
        color= "Red";
    }

    return (text, color);
}

I want to return both strings: text and color, but I am not sure what the problem is.

Error @ return statement:

(parameter) ? text/color

Cannot convert lambda expression to type 'string' because it is not a delegate type

like image 839
Nithraw Avatar asked May 09 '14 14:05

Nithraw


People also ask

Can I return 2 values from a function in C?

In C or C++, we cannot return multiple values from a function directly.

Can you have 2 returns in a function?

You can't return two values. However, you can return a single value that is a struct that contains two values. Show activity on this post. You can return only one thing from a function.

Can return return 2 values?

Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.


2 Answers

When you are returning two things, you need to declare your function as returning two things. However, your function is declared as returning one string.

One way to fix it is using Tuple<T1,T2>:

Tuple<string,string> Active_Frozen(string text, string color) {
    ...
    return Tuple.Create(text, color);
}

Note that returning the name of the color, rather than a color object itself, may not be ideal, depending on the use of the returned values in your design. If you wish to return an object representation of the color instead of a string, change the second type argument of the Tuple, or create your own class that represents the text and its color.

like image 126
Sergey Kalinichenko Avatar answered Oct 12 '22 04:10

Sergey Kalinichenko


Make a class and return a class object from the method:

public class Container
{
    public string text {get;set;}
    public string color{get;set;}
}

Method:

protected Container Active_Frozen(string text, string color)
{
    connection();

    string query = "SELECT CustomerInfo FROM ActiveSubscription WHERE UserName=@UserName";

    SqlCommand cmd = new SqlCommand(query, conn);


    if(query=="true")
    {
        Container c = new Container{text = "Frozen", color= "Red"};
    }

    else
    {
        Container c = new Container{text = "Frozen", color= "Red"};
    }

    return c;
}
like image 42
Ehsan Sajjad Avatar answered Oct 12 '22 04:10

Ehsan Sajjad