How to Concatenate Objects in C#?
Not just strings.
String concatenation is a very simple operation that allows you to join multiple strings together. The usual way to do this is to use the ‘+’ operator:
string greeting = "Hello, " + "World!";
Additionally, there are several other ways to concatenate strings: using Join
, Concat
, Format
methods of string
class or using a StringBuilder
class:
var sb = new StringBuilder();string greeting = sb.Append("Hello, ").Append("World!").ToString();
String concatenation is a simple thing, and every developer can write a compiled example without an IDE on a piece of paper.
But what about objects concatenation? Can this be done as elegantly as string concatenation? Yes, it can.
There are two instances of a Person
class:
The goal is to combine the person1
and person2
objects in the same way as we usually do with strings, to get the following result: