getting out values from string format c#

366 views Asked by At

I have this line of code

merchant = string.Format("{0} {1}", person.FirstName, person.LastName);
what is the correct way to get values out of the variable using . notation?
Is there a way from this to do that?

3

There are 3 answers

0
Uzair Ahmed Siddiqui On BEST ANSWER

Make Merchent a type first so you can access the properties of its object with "." notation.

public class Merchant
{
public string Firstname {get;set;}
public string Lastname {get;set;}
// any other properties of merchant
}

Then you can access it in the main class like this .

Merchant m = new Merchant(){ Firstname=person.FirstName, Lastname= person.Lastname };
string a = m.Firstname;
string b = m.Lastname;
4
ZuoLi On

If this is some kind of serialization and you just need to parse the result string later, then the following code can help you:

merchant = string.Format("{0} {1}", person.FirstName, person.LastName); 
var result = merchant.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// this ^ won't work if firstName or lastName contain spaces, so you can use another separator:
merchant = string.Format("{0}#{1}", person.FirstName, person.LastName); 
var result = merchant.Split("#", StringSplitOptions.RemoveEmptyEntries);

var firstName = result[0];
var lastName = result[1];

But it is not an object, it is just a string.

0
Richnau On

The thing you are doing is merging two separate strings into one new string. There is no way of getting back the initial strings from the result string without beforehand knowing the exact length of the input strings (in which case you would be able to use String.Substring).