Close

c# – Embed variables in a string using the substition technique

Previously in the boolean chapter we saw:

[csharp]

using System;

class BooleanDemo
{
static void Main()
{
bool myFirstBoolean = 3 + 2 == 5;
Console.WriteLine(myFirstBoolean.ToString());

bool mySecondBoolean = 3 + 2 => 5;
Console.WriteLine(mySecondBoolean.ToString());

// Here we use the ‘and’, "&&" operator
bool BothAreTrue = myFirstBoolean && mySecondBoolean ;
Console.WriteLine("Are both true: " + BothAreTrue.ToString() + " That’s becuase one of them is false");

// Here we use the ‘or’, "||" operator
bool IsOneTrue = myFirstBoolean || mySecondBoolean ;
Console.WriteLine("Are both true: " + IsOneTrue.ToString() + + " That’s because only of them them needs to be true");

}
}
[/csharp]

We can use a technique called substitution as a shorthand, and simpler way to embed objects in strings. It works by embedding curly-braced-numbers in the string, e.g.:

[csharp]

using System;
class SubstitionTechnique
{
static void Main()
{
bool myFirstBoolean = 3 + 2 == 5;
Console.WriteLine(myFirstBoolean.ToString());

bool mySecondBoolean = 3 + 2 => 5;
Console.WriteLine(mySecondBoolean.ToString());

// Here we use the ‘and’, "&&" operator
bool BothAreTrue = myFirstBoolean && mySecondBoolean ;
Console.WriteLine("Are both true: {0}. That’s becuase one of them is false", BothAreTrue);

// Here we use the ‘or’, "||" operator
bool IsOneTrue = myFirstBoolean || mySecondBoolean ;
Console.WriteLine("Are both true: {0}. That’s because only of them them needs to be true", IsOneTrue);

}
}
[/csharp]

The linux Awk command works in a similar way.

Also see:

http://msdn.microsoft.com/en-us/library/fk49wtc1%28v=vs.110%29.aspx