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

Previously in the boolean chapter we saw:


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");

	}
}

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.:


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);

	}
}        

The linux Awk command works in a similar way.

Also see:

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