Saturday, January 8, 2011

C# function returning multiple values

Python functions can return multiple values.
 class  MultiValueFunctionExperiment(object): 
 
      def  MyFunctionWithMultiValues(self): 
         return 1, 2, "Toto"
 
      def  Demo(self): 
         a, b, s =  self. MyFunctionWithMultiValues() 
         print  a
         print  b
         print  s
 
 e =  MultiValueFunctionExperiment() 
 e. Demo() 

I like to do the same in C#. Here is the syntax I came with by using a class named MultiValue.

 class  MultiValueFunctionExperiment  {
 
     private MultiValue MyFunctionWithMultiValues() { 
 
         return new MultiValue().Add(1).Add(2).Add("Toto");
     }
     public void Demo() { 
 
         MultiValue mv = MyFunctionWithMultiValues();
         int a         = mv.Value<int >();
         int b         = mv.Value<int >();
         string s      = mv.Value<string >();
 
         Console.WriteLine(a);
         Console.WriteLine(b);
         Console.WriteLine(s);
     }
 }
 

Here is the class MultiValue

 class MultiValue  { 
 
     List<object > _values;
 
     public MultiValue(){
 
         _values = new  List<object >();
     }
     public MultiValue Add(object  i) { 
 
         this ._values.Add(i);
         return  this ;
     }
     public T Value<T>() { 
 
         T i = (T)this ._values[0];
         this ._values.RemoveAt(0);
         return  i;
     }
 }

No comments:

Post a Comment