0

I've just started c# and I was trying to do some basic algorithms, I wanted to know if there's a way to assign two variables at once but different values as in python you can use:

n1, n2 = map(int, input("Input Numbers").split(","))

is there a way to do the same thing in c# by using a function

Jay_ gov
  • 55
  • 1
  • 10
  • It's not clear what you are asking here. Do you want to write your own function or something else? – DavidG Nov 02 '21 at 12:51
  • Yes, you can "assign two variables at once but different values". It's called [`Deconstruct`](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct) but you cannot do it to `Split` unless you write your own `Deconstruct` extension method for arrays. – Sweeper Nov 02 '21 at 12:54
  • i want to build my own function.. – Jay_ gov Nov 02 '21 at 12:54
  • No, not like that. C# is not as high level as python. The size of the input needs to be known at compile time. Just make a `n` a `List` instead of using `n1` `n2`... It's better anyhow. I mean, what should happen when you enter three or only one number? – JHBonarius Nov 02 '21 at 12:55
  • So I wanted to post an answer, because I think this is an XY problem: you are asking the wrong question. But it was closed, so no go. – JHBonarius Nov 02 '21 at 13:06

3 Answers3

2

Yes, it is possible with Tuples

(n1, n2) = myFunction();

private (int first, string second) myFunction()
{
    return (123, "Hello World");
}

Bizhan
  • 16,157
  • 9
  • 63
  • 101
TJ Rockefeller
  • 3,178
  • 17
  • 43
0

I believe you're asking about tuple unpacking. It is available in C#.

public class Example
{
    public static void Main()
    {
        // explicit tuple:
        var result = QueryCityData("New York City");

        var city = result.Item1;
        var pop = result.Item2;
        var size = result.Item3;

        // unpacking:

        var (city, pop, size) = QueryCityData("New York City");
    }

    private static (string, int, double) QueryCityData(string name)
    {
        if (name == "New York City")
            return (name, 8175133, 468.48);

        return ("", 0, 0);
    }
}

then:

Agent_L
  • 4,960
  • 28
  • 30
0

I think the closest thing to that would be tuples and their deconstructions like this:
var (name, address, city, zip) = contact.GetAddressInfo();
For more info see: Deconstructing tuples and other types

But in general, in C# it's not that common like it's in python.

Just Shadow
  • 10,860
  • 6
  • 57
  • 75
  • yeah, that's deconstructing. But you cannot simply split a string into substrings, convert each item to an int and deconstruct that with such a simple one-liner. you'll have to wirte your own parsing. – JHBonarius Nov 02 '21 at 12:55