user4094175
user4094175

Reputation:

return multiple values from method using out string in c#

The LoadEmployee is a method too and I'am facing an error says:The out parameters 'Firstname' must be assigned to before control leaves the current method is there other way to return value without using out parameter

  protected void SplitName(string Name, out string FirstName, out string MiddleName)
    {

        char[] delimiterChars = { ',' };
        string[] name = acEmployee.Text.Split(delimiterChars);
        string Lastname = name[0];
        string middlename = name[1].Substring(Math.Max(0, name[1].Length - 1));
        string Firstname = name[1] = name[1].Remove(name[1].Length - 1);

    }


  private void LoadEmployee()

    {

        string name = acEmployee.Text;
        string firstname, middlename;
        SplitName(name,out firstname,out middlename);
    }

Upvotes: 0

Views: 92

Answers (3)

mrtsl7
mrtsl7

Reputation: 81

You have to delete string tags because you have already declared them in (protected void SplitName(string Name, out string FirstName, out string MiddleName))

name = acEmployee.Text.Split(delimiterChars); Lastname = name[0]; middlename = name[1].Substring(Math.Max(0, name[1].Length - 1)); Firstname = name[1] = name[1].Remove(name[1].Length - 1);

Upvotes: 0

vallabha
vallabha

Reputation: 385

You should assign values to the out parameters, so replace the below

  string middlename = name[1].Substring(Math.Max(0, name[1].Length - 1));
  string Firstname = name[1] = name[1].Remove(name[1].Length - 1);

with

  MiddleName= name[1].Substring(Math.Max(0, name[1].Length - 1));
  FirstName= name[1] = name[1].Remove(name[1].Length - 1);

Upvotes: 0

David Pilkington
David Pilkington

Reputation: 13620

You cannot have them as local variables as you need to assign a value to the parameters you are passing in

protected void SplitName(string Name, out string FirstName, out string MiddleName)
{

    char[] delimiterChars = { ',' };
    string[] name = acEmployee.Text.Split(delimiterChars);
    string Lastname = name[0];
    Middlename = name[1].Substring(Math.Max(0, name[1].Length - 1));
    Firstname = name[1] = name[1].Remove(name[1].Length - 1);

}

What you could also do is have an object that wraps all of the names

public class Name
{
    public string FirstName {get; set;}
    public string MiddleName {get; set;}
    public string LastName {get; set;}
}

and then you can return that from you method

protected Name SplitName(string Name)

Upvotes: 1

Related Questions