Search code examples
c#lambdafuncstring-interpolation

Can one place Lambdas or Func's in String Interpolation statements


Consider the following;

    public override string ToString()
    {

        return $"{HouseName}{StreetLine1 + " : "}{StreetLine2}{PostalTown + " : "}:{PostCode + " : "}{Country}";
    }

This is nothing more than a simple override of ToString() to give end users in an application a little more meaningful information about an address entity than they would otherwise get were no override provided.

HouseName, StreetLine2 and Country are all allowed null values on the backend database. I am wondering if rather than writing separate methods to determine the value of these and then return either nothing or the value + " : " there is a way to do this via a Lambda or func within the actual string interpolation statement itself.

I am still learning my way around C# and what searching I have done to date seems to indicate that this probably isn't possible even with the magical Elvis operator. However it's equally possible that I've simply misunderstood what I have been reading.

EDIT

Following @Evk's answer I created the following quick console app.

    namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var adr = new Address { StreetLine1 = "1 Any Road", PostalTown = "Any Town", PostCode = "AB12 3CD" };
            Console.WriteLine($"{(adr.HouseName != null ? " : " + adr.HouseName : "")} : {adr.StreetLine1 } : { (adr.StreetLine2 != null ? " : " + adr.StreetLine2 : "")} : {adr.PostalTown} : {adr.PostCode} ");
            Console.ReadLine();
        }
    }

    public class Address
    {
        public string HouseName { get; set; }


        public string StreetLine1 { get; set; }

        public string StreetLine2 { get; set; }

        public string PostalTown { get; set; }


        public string PostCode { get; set; }

        public string Country { get; set; }
    }
}

This produced the following result

 : 1 Any Road :  : Any Town : AB12 3CD

In reality I was after

 1 Any Road : Any Town : AB12 3CD

and as you can see I have not even factored in Country , which had it been set should have produced;

 1 Any Road : Any Town : AB12 3CD : Any Country

Solution

  • if rather than writing separate methods to determine the value of these and then return either nothing or the value + " : " there is a way to do this within the actual string interpolation statement itself

    You can use "?:" operator, just enclose it in "()":

    $"{StreetLine1 + (StreetLine2 != null ? " : " + StreetLine2 : "")}";
    

    However if you just need to join bunch of strings together - use String.Join:

    String.Join(" : ", new[] {HouseName, StreetLine1, StreetLine2}.Where(c => c != null));