Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string as multiple parameters?

Hey guys I'm fairly new to C# and I'm wondering if there's an easy way to pass a string as multiple parameters. Here's an example:

I want to pass to a function that takes these parameters:

DoStuff(int a, string b, string c, string d)

I have a string, say "string e" that contains the following: 1,a,b,c

So I'd like to call the function like so, DoStuff(e). But of course this results in errors because it expects more parameters. Is there a simple way to pass my string of parameters to the function?

EDIT: Thanks for all the advice on function overloads. This function is a class constructor, can it have overloads? Here's the code

arrayvariable[count] = new DoStuff(e);
like image 736
rumsey Avatar asked Nov 20 '25 08:11

rumsey


2 Answers

You would need to make an overload of the method which takes a single string. It could then split the string and create the appropriate parameters.

For example:

void DoStuff(int a, string b, string c, string d)
{
    // Do your stuff...
}

void DoStuff(string parameters)
{
    var split = parameters.Split(',');
    if (split.Length != 4)
          throw new ArgumentException("Wrong number of parameters in input string");

    int a;
    if (!int.TryParse(split[0], out a)
          throw new ArgumentException("First parameter in input string is not an integer");

    // Call the original
    this.DoStuff(a, split[1], split[2], split[3]);
}

Granted, it would be possible to refactor this into a method which could make the string parsing more generic, and reusable, if this is something you'll be doing often.

like image 147
Reed Copsey Avatar answered Nov 21 '25 21:11

Reed Copsey


public void DoStuff( int a, string b, string c, string d )
{
    //your code here
}

public void DoStuff( string e )
{
   string[] splitE = e.Split( ',' );

   int a;
   int.TryParse( splitE[0], out a );

   DoStuff( a, splitE[1], splitE[2], splitE[3] );
}

You'll need additional error checking for the splitting and parsing of the int, but that should do it for you

like image 44
Brian Dishaw Avatar answered Nov 21 '25 22:11

Brian Dishaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!