Method must return multiple values

Hii

I have a method in C #, I have to return multiple values ​​from this method using commands like arrays. Is there a reliable way?

+6
c #
source share
7 answers

Well, you could use:

  • custom class / structure / type containing all your values
  • out parameters

i.e:.

 class MyValues { public string Val1 { get; set; } public int Val2 {get; set; } } public MyValues ReturnMyValues(); 

or

 public void ReturnMyValues(out string Val1, out int Val2); 
+10
source share

Yes, the out keyword:

 public void ReturnManyInts(out int int1, out int int2, out int int3) { int1 = 10; int2 = 20; int3 = 30; } 

then name it like this:

 int i1, i2, i3; ReturnManyInts(out i1, out i2, out i3); Console.WriteLine(i1); Console.WriteLine(i2); Console.WriteLine(i3); 

which outputs:

 10 20 30 

EDIT:

I see that many posts suggest creating your own class for you. This is optional since .net provides you with a class to do what they say already. Class Tuple .

 public Tuple<int, string, char> ReturnMany() { return new Tuple<int, string, char>(1, "some string", 'B'); } 

then you can get it like this:

 var myTuple = ReturnMany(); myTuple.Item1 ... myTuple.Item2 ... 

There are general overloads, so you can have up to 8 unique types in your tuple.

+15
source share

If you are using .NET 4.0, you can use one of the generic Tuple to return multiple values ​​from a method call. The static Tuple class provides methods for creating Tuple objects. Therefore, you do not need to define your own return type for the method.

 public Tuple<string,int> Execute() { return new Tuple<string,int>("Hello World", 2); } 
+5
source share

Yes, it can create a new type that will contain several properties, and then return this type:

 public MyType MyMethod() { return new MyType { Prop1 = "foo", Prop2 = "bar" }; } 
+2
source share

Why is using "out" unreliable? (Or did you make a typo and mean without?)

There are several methods:

  • Returns an object that contains multiple values ​​(structure / class, etc.)
  • out
  • ref
+2
source share

Descriptor class or structure. You should put it somewhere, since it is logical that the method should return only one value. Alternatively, you can use out or ref, but I would return a class.

Btw, what keeps you from using collections?

0
source share
 public int Method Name(out string stringValue, out int intValue) { /// Method goes here /// return intVaraible } 

here you get 3 return values ​​1. stringValue 2. intValue 3. intVariable

0
source share

All Articles