c# variable in string code example

Example 1: c sharp string interpolation

// To use interpolation in strings, put the name of the relevant
// variable between brackets {} and put a dollar sign $ in front
// of the string. This will tell C# to use interpolation.
double a = 3;
double b = 4;
Console.WriteLine($"Area of {a} and {b} is {0.5 * a * b}");

Example 2: C# write a variable in string

// Method 1 Interpolation
//Interpolation Strings are strings that are interpertated at run time for your local vars
//This string must still use escape chars such as \\ and '{' char must be typed twice to show up.
int Num = 1;
String InterpolationString = $"The numer is {Num}. this way {{ can mark values"
//the intel on this web app has not incorperated this sense yet

// Method 2 Format 
string StringToFormat = "Name:{0} {1}, Location:{2}, Age:{3}";
string FormattedString = string.Format(StringToFormat, "Jim", "Bean", "EU", 1);
// You van add more variables to a sting by just adding {x} to root sting 
// format (where x is the variable spot in the input) and another var to the 
// of end params

// you can also add format specifications to a var.
int Num = 10;
Console.Write("{X4}");
// Output: 000A (Hexdecimal or base16 10)
//Here are some of the following
//"C" or "c" 	Currency
//"D" or "d" 	Decimal
//"E" or "e" 	Exponential (scientific)
//"F" or "f" 	Fixed-point
//"G" or "g" 	General
//"N" or "n" 	Number
//"P" or "p" 	Percent
//"X" or "x" 	Hexadecimal
//"R" or "r" 	Round-trip
//See https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings for more

Example 3: c# write variable in string

int age = 22;

Console.WriteLine($"Age: {age}");

Example 4: c# viariable in string

string name = "Mark";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.