0

How can i initialise the FullName variable to auto concat the previous two strings?

Due to system design and constraints I can't pass the concatenated string when initialising, so is there a way to initialise the FullName variable without providing the concat string initially?

    public class Person
    {
        public String FirstName { get; set; }
        public String SecondName { get; set; }

        //this should be first and second name together
        public String FullName{ get; set;}
    }
Dawson
  • 573
  • 6
  • 24

4 Answers4

4

FullName is not a real property and should have only a getter

public String FullName
{
   get { return string.Format("{0} {1}", FirstName, LastName); }
}

and this is NOT java.. you can use string

UPDATE

please stop concating string and start formatting them or building them with StringBuilder.. String output: format or concat in C#?

Community
  • 1
  • 1
ymz
  • 6,602
  • 1
  • 20
  • 39
  • In this circumstance what's wrong with doing a simple string concatenation? – Enigmativity Jan 19 '16 at 06:13
  • in ANY circumstance it is wrong to use it - you are actually messing up your memory for nothing and spending computing resources with no good reason... it is a bad habit that developers use for some reason over and over again – ymz Jan 19 '16 at 07:53
  • 1
    @ymz - Don't forget to do an `@` notification - it was just luck that I kept this page open. Nonetheless, string concatenation **doesn't** mess up memory - The garbage collector is perfectly able to clean up after small objects nicely. Computing resources are cheap these days and the resources required to clean up a single concatenation is almost infinitesimally negligible. Besides, the source for `String.Format` almost immediately goes and calls `Format(null, format, new Object[] {arg0, arg1})` which has created some garbage to be collected. It then goes on to create a `StringBuilder`, etc. – Enigmativity Jan 19 '16 at 13:46
1

What about:

public class Person
{
    public String FirstName { get; set; }
    public String SecondName { get; set; }

    //this should be first and second name together
    public String FullName{ get { return FirstName + " " + SecondName; } }
}
serhiyb
  • 4,753
  • 2
  • 15
  • 24
1

I don't have VS with me right now so syntax may be slightly off, but:

public String FullName{ get { return FirstName + " " + SecondName; }

Should do it - not there is no setter anymore since FullNames value is derived from FirstName and SecondName.

John3136
  • 28,809
  • 4
  • 51
  • 69
0

it is a little bit faster:

public String FullName{ get { return String.Concat(FirstName, " ", SecondName); }}

But String.Format(...) is clear and easy to modify.

Andrey Burykin
  • 700
  • 11
  • 23