c# string $ formatting code example

Example 1: string format c#

using System;

namespace FormatingTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "Name:{0} {1}, Location:{2}, Age:{3}";
            string msg = string.Format(s, "Ram", "Singh", "Mumbai", 32);
            Console.WriteLine("Format Result: {0}", msg);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Example 2: c# formatting

// 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

Tags:

Java Example