Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Returning mixed types in a function

Tags:

c#

object

return

I have some different data types that i need to do something with in a function. Those data needs to be processed in the function and returned as an object i believe it is called.

This is some not tested code i just wrote here, but i think it displays what im trying to do .. I hope you guys can help me out how to do it.

private void Button_Click(object sender, RoutedEventArgs e)
{
     // Here im calling the function which returns data to the object
     object thoseProcessedData = SomeTestObject(5, "ABC", SomeOtherThing);

     // When returned i want to be able to use the different data like so. 
     string useItLikeThis = thoseProcessedData.newString;
     int numbersLikeThis = thoseProcessedData.newNumber;
}

public object SomeTestObject(int numbers, string letters, AnotherType anothertype)
{

     string newString = letters.Substring(0,5);
     int newNumber = numbers + 10;
     AnotherType newType = anothertype.Something();

     return processedData;
}

Please guys dont kill me, if this is a too stupid question. Im still very new to C# ..

If you dont get what im trying to do, please ask! Since my english is not the best i thought this way would be the best to show you what i want..

like image 629
Daniel Jørgensen Avatar asked Feb 12 '23 20:02

Daniel Jørgensen


1 Answers

Create class which holds data you want to pass and return:

public class Data
{
   public string Letters { get; set; }
   public int Number { get; set; }
   public AnotherType Thing { get; set; }
}

Pass it to method:

var data = new Data { Letters = "ABC", Number = 5, Thing = SomeOtherThing };
DoSomething(data);
// here data will have modified values

Thus class is a reference type, all changes to its members inside DoSomething method, will be reflected in your data object reference. So, changes can look like:

public void DoSomething(Data data)
{
     data.Letters = data.Letters.Substring(0,5);
     data.Number += 10;
     data.Thing.Something();
}
like image 94
Sergey Berezovskiy Avatar answered Feb 15 '23 10:02

Sergey Berezovskiy