How to use a literal tuple as property of a class in C#

Asked

Viewed 43 times

2

Hello, I’m working with C# and I read about literal tuples. With that, I’m creating the class below:

public class Foo 
{
    public (int bar, string bin)? barBin { get; set; }
}

In theory, in order for me to be able to use this class and assign values to this tuple, I would do it like this:

int testBar = 2;
string testBin = "hello world";

var foo = new Foo() 
{
    barBin = (bar: testBar, bin: testBin)
};

The problem is that when I use this statement the VS gives me the message An expression tree may not contain a tuple literal. also tried to pass an undeclared tuple (barBin = (testBar, testBin)) but it doesn’t work.

How do I use literal tuples as properties in a class and work on them?

  • 1

    Here it works, are you using the right version? But I already say that doing this is abuse of the tuple, I saw no reason to use it there. Actually I don’t think it’s even compiling this code posted.

  • 1

    Here is also ok, sure that the version you are using does not allow the use of literal tuples.

  • 1

    What exactly you are wanting to do, the error is in the code exposed in the question or in another scenario that you have not demonstrated here?

  • I am using C#7, the use of the tuple is to understand how far I can use it and its advantages and the error that is being presented is directly in the Main of a simple test project

1 answer

-2

Just to remind you. The Tuple class was introduced in . NET Framework 4.0.

static void Main(string[] args)
{
   var person = GetPerson();
}

static Tuple<int, string> GetPerson() 
{
   return Tuple.Create(1, "Fulano");
}

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.