C# format string 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# string formatting

name = "Bob";
age = 27;
info = $"Your name is {name} and you are {age} years old";

Example 3: c# trim string

string hello = " hello world ";
hello.Trim();

Example 4: to string c# fields

public override String ToString()
    {
     	Type objType = this.GetType();
     	PropertyInfo[] propertyInfoList = objType.GetProperties();
     	StringBuilder result = new StringBuilder();
     	foreach (PropertyInfo propertyInfo in propertyInfoList)
      	   result.AppendFormat("{0}:{1},", propertyInfo.Name, propertyInfo.GetValue(this));
          
     	 return "{" + result.ToString() + "}";
     }