Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to separate first and last name from variable

I have a property:

public string Name {get; set;}

that receives both first name and last name as a single string. How do I separate it into different strings? Since there is no actual name yet, Name.Split(‘ ‘) does not work.

edit: if i try to create a string array such as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string[] nameSplit = Name.Split(' ');

there is a "field initializer cannot reference the non-static field, method or property Student.Name" (Student being the class that Name property belongs to).

>Solution :

You can split the Name.set value when you get it and combine the seperate values when Name.get is called. Im not checking for nulls or spaces etc here, I leave that up to you.

public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Name
        {
            get
            {
                return $"{FirstName} {LastName}";
            }
            set
            {
                var parts = value.Split(' ');
                FirstName = parts[0];
                LastName = parts[1];
            }
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading