System.ParameterizedStrings.FormatPrintF C# (CSharp) Method

FormatPrintF() static private method

Formats an argument into a printf-style format string.
static private FormatPrintF ( string format, object arg ) : string
format string The printf-style format string.
arg object The argument to format. This must be an Int32 or a String.
return string
                static unsafe string FormatPrintF(string format, object arg)
                {
			// Determine how much space is needed to store the formatted string.
			string stringArg = arg as string;
			int neededLength = stringArg != null ?
				snprintf(null, IntPtr.Zero, format, stringArg) :
				snprintf(null, IntPtr.Zero, format, (int)arg);
			if (neededLength == 0)
				return string.Empty;
			if (neededLength < 0)
				throw new InvalidOperationException("The printf operation failed");
			
			// Allocate the needed space, format into it, and return the data as a string.
			byte[] bytes = new byte[neededLength + 1]; // extra byte for the null terminator
			fixed (byte* ptr = bytes){
				int length = stringArg != null ?
					snprintf(ptr, (IntPtr)bytes.Length, format, stringArg) :
					snprintf(ptr, (IntPtr)bytes.Length, format, (int)arg);
				if (length != neededLength)
				{
					throw new InvalidOperationException("Invalid printf operation");
				}
			}
			return StringFromAsciiBytes(bytes, 0, neededLength);
                }