diff --git a/snippets/csharp/System/BadImageFormatException/Overview/condition1.cs b/snippets/csharp/System/BadImageFormatException/Overview/condition1.cs index 66e73c2635c..750fce2db76 100644 --- a/snippets/csharp/System/BadImageFormatException/Overview/condition1.cs +++ b/snippets/csharp/System/BadImageFormatException/Overview/condition1.cs @@ -3,26 +3,28 @@ public class Example { - public static void Main() - { - // - // Windows DLL (non-.NET assembly) - string filePath = Environment.ExpandEnvironmentVariables("%windir%"); - if (!filePath.Trim().EndsWith(@"\")) - filePath += @"\"; - filePath += @"System32\Kernel32.dll"; + public static void Main() + { + // + // Windows DLL (non-.NET assembly) + string filePath = Environment.ExpandEnvironmentVariables("%windir%"); + if (!filePath.Trim().EndsWith(@"\")) + filePath += @"\"; + filePath += @"System32\Kernel32.dll"; - try { - Assembly assem = Assembly.LoadFile(filePath); - } - catch (BadImageFormatException e) { - Console.WriteLine("Unable to load {0}.", filePath); - Console.WriteLine(e.Message.Substring(0, - e.Message.IndexOf(".") + 1)); - } - // The example displays an error message like the following: - // Unable to load C:\WINDOWS\System32\Kernel32.dll. - // The module was expected to contain an assembly manifest. - // - } + try + { + Assembly assem = Assembly.LoadFile(filePath); + } + catch (BadImageFormatException e) + { + Console.WriteLine($"Unable to load {filePath}."); + Console.WriteLine(e.Message.Substring(0, + e.Message.IndexOf(".") + 1)); + } + // The example displays an error message like the following: + // Unable to load C:\WINDOWS\System32\Kernel32.dll. + // The module was expected to contain an assembly manifest. + // + } } diff --git a/snippets/csharp/System/BadImageFormatException/Overview/stringlib.cs b/snippets/csharp/System/BadImageFormatException/Overview/stringlib.cs index 03f1763ab3e..49f0863e3bd 100644 --- a/snippets/csharp/System/BadImageFormatException/Overview/stringlib.cs +++ b/snippets/csharp/System/BadImageFormatException/Overview/stringlib.cs @@ -1,38 +1,38 @@ -// +// using System; public class StringLib { - private string[] exceptionList = { "a", "an", "the", "in", "on", "of" }; - private char[] separators = { ' ' }; + private string[] exceptionList = { "a", "an", "the", "in", "on", "of" }; + private char[] separators = { ' ' }; - public string ToProperCase(string title) - { - bool isException = false; + public string ToProperCase(string title) + { + bool isException = false; - string[] words = title.Split( separators, StringSplitOptions.RemoveEmptyEntries); - string[] newWords = new string[words.Length]; - - for (int ctr = 0; ctr <= words.Length - 1; ctr++) - { - isException = false; + string[] words = title.Split(separators, StringSplitOptions.RemoveEmptyEntries); + string[] newWords = new string[words.Length]; - foreach (string exception in exceptionList) - { - if (words[ctr].Equals(exception) && ctr > 0) + for (int ctr = 0; ctr <= words.Length - 1; ctr++) + { + isException = false; + + foreach (string exception in exceptionList) { - isException = true; - break; + if (words[ctr].Equals(exception) && ctr > 0) + { + isException = true; + break; + } } - } - if (!isException) - newWords[ctr] = words[ctr].Substring(0, 1).ToUpper() + words[ctr].Substring(1); - else - newWords[ctr] = words[ctr]; - } - return string.Join(" ", newWords); - } + if (!isException) + newWords[ctr] = words[ctr].Substring(0, 1).ToUpper() + words[ctr].Substring(1); + else + newWords[ctr] = words[ctr]; + } + return string.Join(" ", newWords); + } } // Attempting to load the StringLib.dll assembly produces the following output: // Unhandled Exception: System.BadImageFormatException: diff --git a/snippets/csharp/System/BadImageFormatException/Overview/targetplatform1.cs b/snippets/csharp/System/BadImageFormatException/Overview/targetplatform1.cs index 55c710aa404..364e8e3fc22 100644 --- a/snippets/csharp/System/BadImageFormatException/Overview/targetplatform1.cs +++ b/snippets/csharp/System/BadImageFormatException/Overview/targetplatform1.cs @@ -5,39 +5,45 @@ public class Example { - public static void Main() - { - String[] args = Environment.GetCommandLineArgs(); - if (args.Length == 1) { - Console.WriteLine("\nSyntax: PlatformInfo \n"); - return; - } - Console.WriteLine(); + public static void Main() + { + string[] args = Environment.GetCommandLineArgs(); + if (args.Length == 1) + { + Console.WriteLine("\nSyntax: PlatformInfo \n"); + return; + } + Console.WriteLine(); - // Loop through files and display information about their platform. - for (int ctr = 1; ctr < args.Length; ctr++) { - string fn = args[ctr]; - if (!File.Exists(fn)) { - Console.WriteLine("File: {0}", fn); - Console.WriteLine("The file does not exist.\n"); - } - else { - try { - AssemblyName an = AssemblyName.GetAssemblyName(fn); - Console.WriteLine("Assembly: {0}", an.Name); - if (an.ProcessorArchitecture == ProcessorArchitecture.MSIL) - Console.WriteLine("Architecture: AnyCPU"); - else - Console.WriteLine("Architecture: {0}", an.ProcessorArchitecture); - - Console.WriteLine(); + // Loop through files and display information about their platform. + for (int ctr = 1; ctr < args.Length; ctr++) + { + string fn = args[ctr]; + if (!File.Exists(fn)) + { + Console.WriteLine($"File: {fn}"); + Console.WriteLine("The file does not exist.\n"); } - catch (BadImageFormatException) { - Console.WriteLine("File: {0}", fn); - Console.WriteLine("Not a valid assembly.\n"); + else + { + try + { + AssemblyName an = AssemblyName.GetAssemblyName(fn); + Console.WriteLine($"Assembly: {an.Name}"); + if (an.ProcessorArchitecture == ProcessorArchitecture.MSIL) + Console.WriteLine("Architecture: AnyCPU"); + else + Console.WriteLine($"Architecture: {an.ProcessorArchitecture}"); + + Console.WriteLine(); + } + catch (BadImageFormatException) + { + Console.WriteLine($"File: {fn}"); + Console.WriteLine("Not a valid assembly.\n"); + } } - } - } - } + } + } } // diff --git a/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String.cs b/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String.cs index b9dee88d991..8330a9621e1 100644 --- a/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String.cs +++ b/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String.cs @@ -3,56 +3,59 @@ public class Example { - public static void Main() - { - // Define an array of 20 elements and display it. - int[] arr = new int[20]; - int value = 1; - for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) { - arr[ctr] = value; - value = value * 2 + 1; - } - DisplayArray(arr); + public static void Main() + { + // Define an array of 20 elements and display it. + int[] arr = new int[20]; + int value = 1; + for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) + { + arr[ctr] = value; + value = value * 2 + 1; + } + DisplayArray(arr); - // Convert the array of integers to a byte array. - byte[] bytes = new byte[arr.Length * 4]; - for (int ctr = 0; ctr < arr.Length; ctr++) { - Array.Copy(BitConverter.GetBytes(arr[ctr]), 0, - bytes, ctr * 4, 4); - } + // Convert the array of integers to a byte array. + byte[] bytes = new byte[arr.Length * 4]; + for (int ctr = 0; ctr < arr.Length; ctr++) + { + Array.Copy(BitConverter.GetBytes(arr[ctr]), 0, + bytes, ctr * 4, 4); + } - // Encode the byte array using Base64 encoding - String base64 = Convert.ToBase64String(bytes); - Console.WriteLine("The encoded string: "); - for (int ctr = 0; ctr <= base64.Length / 50; ctr++) - Console.WriteLine(base64.Substring(ctr * 50, - ctr * 50 + 50 <= base64.Length - ? 50 : base64.Length - ctr * 50)); - Console.WriteLine(); + // Encode the byte array using Base64 encoding + string base64 = Convert.ToBase64String(bytes); + Console.WriteLine("The encoded string: "); + for (int ctr = 0; ctr <= base64.Length / 50; ctr++) + Console.WriteLine(base64.Substring(ctr * 50, + ctr * 50 + 50 <= base64.Length + ? 50 : base64.Length - ctr * 50)); + Console.WriteLine(); - // Convert the string back to a byte array. - byte[] newBytes = Convert.FromBase64String(base64); + // Convert the string back to a byte array. + byte[] newBytes = Convert.FromBase64String(base64); - // Convert the byte array back to an integer array. - int[] newArr = new int[newBytes.Length/4]; - for (int ctr = 0; ctr < newBytes.Length / 4; ctr ++) - newArr[ctr] = BitConverter.ToInt32(newBytes, ctr * 4); + // Convert the byte array back to an integer array. + int[] newArr = new int[newBytes.Length / 4]; + for (int ctr = 0; ctr < newBytes.Length / 4; ctr++) + newArr[ctr] = BitConverter.ToInt32(newBytes, ctr * 4); - DisplayArray(newArr); - } + DisplayArray(newArr); + } - private static void DisplayArray(Array arr) - { - Console.WriteLine("The array:"); - Console.Write("{ "); - for (int ctr = 0; ctr < arr.GetUpperBound(0); ctr++) { - Console.Write("{0}, ", arr.GetValue(ctr)); - if ((ctr + 1) % 10 == 0) - Console.Write("\n "); - } - Console.WriteLine("{0} {1}", arr.GetValue(arr.GetUpperBound(0)), "}"); - Console.WriteLine(); - } + private static void DisplayArray(Array arr) + { + Console.WriteLine("The array:"); + Console.Write("{ "); + for (int ctr = 0; ctr < arr.GetUpperBound(0); ctr++) + { + Console.Write($"{arr.GetValue(ctr)}, "); + if ((ctr + 1) % 10 == 0) + Console.Write("\n "); + } + Console.WriteLine($"{arr.GetValue(arr.GetUpperBound(0))} }}"); + Console.WriteLine(); + } } // The example displays the following output: // The array: diff --git a/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String2.cs b/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String2.cs index d6a83721815..4e0cc21c6bd 100644 --- a/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String2.cs +++ b/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String2.cs @@ -3,22 +3,22 @@ public class Example { - public static void Main() - { - // Define a byte array. - byte[] bytes = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; - Console.WriteLine("The byte array: "); - Console.WriteLine(" {0}\n", BitConverter.ToString(bytes)); + public static void Main() + { + // Define a byte array. + byte[] bytes = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; + Console.WriteLine("The byte array: "); + Console.WriteLine($" {BitConverter.ToString(bytes)}\n"); - // Convert the array to a base 64 string. - string s = Convert.ToBase64String(bytes); - Console.WriteLine("The base 64 string:\n {0}\n", s); + // Convert the array to a base 64 string. + string s = Convert.ToBase64String(bytes); + Console.WriteLine($"The base 64 string:\n {s}\n"); - // Restore the byte array. - byte[] newBytes = Convert.FromBase64String(s); - Console.WriteLine("The restored byte array: "); - Console.WriteLine(" {0}\n", BitConverter.ToString(newBytes)); - } + // Restore the byte array. + byte[] newBytes = Convert.FromBase64String(s); + Console.WriteLine("The restored byte array: "); + Console.WriteLine($" {BitConverter.ToString(newBytes)}\n"); + } } // The example displays the following output: // The byte array: diff --git a/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String3.cs b/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String3.cs index da8884fa6a9..7f913c1c879 100644 --- a/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String3.cs +++ b/snippets/csharp/System/Base64FormattingOptions/Overview/ToBase64String3.cs @@ -3,40 +3,39 @@ public class Example { - public static void Main() - { - // Define a byte array. - var bytes = new byte[100]; - int originalTotal = 0; - for (int ctr = 0; ctr <= bytes.GetUpperBound(0); ctr++) { - bytes[ctr] = (byte)(ctr + 1); - originalTotal += bytes[ctr]; - } - // Display summary information about the array. - Console.WriteLine("The original byte array:"); - Console.WriteLine(" Total elements: {0}", bytes.Length); - Console.WriteLine(" Length of String Representation: {0}", - BitConverter.ToString(bytes).Length); - Console.WriteLine(" Sum of elements: {0:N0}", originalTotal); - Console.WriteLine(); + public static void Main() + { + // Define a byte array. + byte[] bytes = new byte[100]; + int originalTotal = 0; + for (int ctr = 0; ctr <= bytes.GetUpperBound(0); ctr++) + { + bytes[ctr] = (byte)(ctr + 1); + originalTotal += bytes[ctr]; + } + // Display summary information about the array. + Console.WriteLine("The original byte array:"); + Console.WriteLine($" Total elements: {bytes.Length}"); + Console.WriteLine($" Length of String Representation: {BitConverter.ToString(bytes).Length}"); + Console.WriteLine($" Sum of elements: {originalTotal:N0}"); + Console.WriteLine(); - // Convert the array to a base 64 string. - string s = Convert.ToBase64String(bytes, - Base64FormattingOptions.InsertLineBreaks); - Console.WriteLine("The base 64 string:\n {0}\n", s); + // Convert the array to a base 64 string. + string s = Convert.ToBase64String(bytes, + Base64FormattingOptions.InsertLineBreaks); + Console.WriteLine($"The base 64 string:\n {s}\n"); - // Restore the byte array. - Byte[] newBytes = Convert.FromBase64String(s); - int newTotal = 0; - foreach (var newByte in newBytes) - newTotal += newByte; + // Restore the byte array. + byte[] newBytes = Convert.FromBase64String(s); + int newTotal = 0; + foreach (byte newByte in newBytes) + newTotal += newByte; - // Display summary information about the restored array. - Console.WriteLine(" Total elements: {0}", newBytes.Length); - Console.WriteLine(" Length of String Representation: {0}", - BitConverter.ToString(newBytes).Length); - Console.WriteLine(" Sum of elements: {0:N0}", newTotal); - } + // Display summary information about the restored array. + Console.WriteLine($" Total elements: {newBytes.Length}"); + Console.WriteLine($" Length of String Representation: {BitConverter.ToString(newBytes).Length}"); + Console.WriteLine($" Sum of elements: {newTotal:N0}"); + } } // The example displays the following output: // The original byte array: diff --git a/snippets/csharp/System/BitConverter/DoubleToInt64Bits/bitstodbl.cs b/snippets/csharp/System/BitConverter/DoubleToInt64Bits/bitstodbl.cs index b53657b6d71..6d9bc814e6f 100644 --- a/snippets/csharp/System/BitConverter/DoubleToInt64Bits/bitstodbl.cs +++ b/snippets/csharp/System/BitConverter/DoubleToInt64Bits/bitstodbl.cs @@ -1,4 +1,4 @@ -// +// // Example of the BitConverter.Int64BitsToDouble method. using System; @@ -7,44 +7,44 @@ class Int64BitsToDoubleDemo const string formatter = "{0,20}{1,27:E16}"; // Reinterpret the long argument as a double. - public static void LongBitsToDouble( long argument ) + public static void LongBitsToDouble(long argument) { double doubleValue; - doubleValue = BitConverter.Int64BitsToDouble( argument ); + doubleValue = BitConverter.Int64BitsToDouble(argument); // Display the argument in hexadecimal. - Console.WriteLine( formatter, - string.Format( "0x{0:X16}", argument ), doubleValue ); + Console.WriteLine(formatter, + $"0x{argument:X16}", doubleValue); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.Int64BitsToDouble( " + - "long ) \nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "long argument", - "double value" ); - Console.WriteLine( formatter, "-------------", - "------------" ); + "long ) \nmethod generates the following output.\n"); + Console.WriteLine(formatter, "long argument", + "double value"); + Console.WriteLine(formatter, "-------------", + "------------"); // Convert long values and display the results. - LongBitsToDouble( 0 ); - LongBitsToDouble( 0x3FF0000000000000 ); - LongBitsToDouble( 0x402E000000000000 ); - LongBitsToDouble( 0x406FE00000000000 ); - LongBitsToDouble( 0x41EFFFFFFFE00000 ); - LongBitsToDouble( 0x3F70000000000000 ); - LongBitsToDouble( 0x3DF0000000000000 ); - LongBitsToDouble( 0x0000000000000001 ); - LongBitsToDouble( 0x000000000000FFFF ); - LongBitsToDouble( 0x0000FFFFFFFFFFFF ); - LongBitsToDouble( unchecked( (long)0xFFFFFFFFFFFFFFFF ) ); - LongBitsToDouble( unchecked( (long)0xFFF0000000000000 ) ); - LongBitsToDouble( 0x7FF0000000000000 ); - LongBitsToDouble( unchecked( (long)0xFFEFFFFFFFFFFFFF ) ); - LongBitsToDouble( 0x7FEFFFFFFFFFFFFF ); - LongBitsToDouble( long.MinValue ); - LongBitsToDouble( long.MaxValue ); + LongBitsToDouble(0); + LongBitsToDouble(0x3FF0000000000000); + LongBitsToDouble(0x402E000000000000); + LongBitsToDouble(0x406FE00000000000); + LongBitsToDouble(0x41EFFFFFFFE00000); + LongBitsToDouble(0x3F70000000000000); + LongBitsToDouble(0x3DF0000000000000); + LongBitsToDouble(0x0000000000000001); + LongBitsToDouble(0x000000000000FFFF); + LongBitsToDouble(0x0000FFFFFFFFFFFF); + LongBitsToDouble(unchecked((long)0xFFFFFFFFFFFFFFFF)); + LongBitsToDouble(unchecked((long)0xFFF0000000000000)); + LongBitsToDouble(0x7FF0000000000000); + LongBitsToDouble(unchecked((long)0xFFEFFFFFFFFFFFFF)); + LongBitsToDouble(0x7FEFFFFFFFFFFFFF); + LongBitsToDouble(long.MinValue); + LongBitsToDouble(long.MaxValue); } } diff --git a/snippets/csharp/System/BitConverter/DoubleToInt64Bits/dbltobits.cs b/snippets/csharp/System/BitConverter/DoubleToInt64Bits/dbltobits.cs index 19ac239b083..7deb2afd87f 100644 --- a/snippets/csharp/System/BitConverter/DoubleToInt64Bits/dbltobits.cs +++ b/snippets/csharp/System/BitConverter/DoubleToInt64Bits/dbltobits.cs @@ -7,45 +7,45 @@ class DoubleToInt64BitsDemo const string formatter = "{0,25:E16}{1,23:X16}"; // Reinterpret the double argument as a long. - public static void DoubleToLongBits( double argument ) + public static void DoubleToLongBits(double argument) { long longValue; - longValue = BitConverter.DoubleToInt64Bits( argument ); + longValue = BitConverter.DoubleToInt64Bits(argument); // Display the resulting long in hexadecimal. - Console.WriteLine( formatter, argument, longValue ); + Console.WriteLine(formatter, argument, longValue); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.DoubleToInt64Bits( " + - "double ) \nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "double argument", - "hexadecimal value" ); - Console.WriteLine( formatter, "---------------", - "-----------------" ); + "double ) \nmethod generates the following output.\n"); + Console.WriteLine(formatter, "double argument", + "hexadecimal value"); + Console.WriteLine(formatter, "---------------", + "-----------------"); // Convert double values and display the results. - DoubleToLongBits( 1.0 ); - DoubleToLongBits( 15.0 ); - DoubleToLongBits( 255.0 ); - DoubleToLongBits( 4294967295.0 ); - DoubleToLongBits( 0.00390625 ); - DoubleToLongBits( 0.00000000023283064365386962890625 ); - DoubleToLongBits( 1.234567890123E-300 ); - DoubleToLongBits( 1.23456789012345E-150 ); - DoubleToLongBits( 1.2345678901234565 ); - DoubleToLongBits( 1.2345678901234567 ); - DoubleToLongBits( 1.2345678901234569 ); - DoubleToLongBits( 1.23456789012345678E+150 ); - DoubleToLongBits( 1.234567890123456789E+300 ); - DoubleToLongBits( double.MinValue ); - DoubleToLongBits( double.MaxValue ); - DoubleToLongBits( double.Epsilon ); - DoubleToLongBits( double.NaN ); - DoubleToLongBits( double.NegativeInfinity ); - DoubleToLongBits( double.PositiveInfinity ); + DoubleToLongBits(1.0); + DoubleToLongBits(15.0); + DoubleToLongBits(255.0); + DoubleToLongBits(4294967295.0); + DoubleToLongBits(0.00390625); + DoubleToLongBits(0.00000000023283064365386962890625); + DoubleToLongBits(1.234567890123E-300); + DoubleToLongBits(1.23456789012345E-150); + DoubleToLongBits(1.2345678901234565); + DoubleToLongBits(1.2345678901234567); + DoubleToLongBits(1.2345678901234569); + DoubleToLongBits(1.23456789012345678E+150); + DoubleToLongBits(1.234567890123456789E+300); + DoubleToLongBits(double.MinValue); + DoubleToLongBits(double.MaxValue); + DoubleToLongBits(double.Epsilon); + DoubleToLongBits(double.NaN); + DoubleToLongBits(double.NegativeInfinity); + DoubleToLongBits(double.PositiveInfinity); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesbool.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesbool.cs index d164668a3bd..003406c47dd 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesbool.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesbool.cs @@ -3,19 +3,19 @@ class Example { - public static void Main( ) - { - // Define Boolean true and false values. - bool[] values = { true, false }; + public static void Main() + { + // Define Boolean true and false values. + bool[] values = { true, false }; - // Display the value and its corresponding byte array. - Console.WriteLine("{0,10}{1,16}\n", "Boolean", "Bytes"); - foreach (var value in values) { - byte[] bytes = BitConverter.GetBytes(value); - Console.WriteLine("{0,10}{1,16}", value, - BitConverter.ToString(bytes)); - } - } + // Display the value and its corresponding byte array. + Console.WriteLine($"{"Boolean",10}{"Bytes",16}\n"); + foreach (bool value in values) + { + byte[] bytes = BitConverter.GetBytes(value); + Console.WriteLine($"{value,10}{BitConverter.ToString(bytes),16}"); + } + } } // The example displays the following output: // Boolean Bytes diff --git a/snippets/csharp/System/BitConverter/GetBytes/byteschar.cs b/snippets/csharp/System/BitConverter/GetBytes/byteschar.cs index ad344df2127..2235b04f319 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/byteschar.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/byteschar.cs @@ -7,30 +7,30 @@ class GetBytesCharDemo const string formatter = "{0,10}{1,16}"; // Convert a char argument to a byte array and display it. - public static void GetBytesChar( char argument ) + public static void GetBytesChar(char argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( char ) " + - "\nmethod generates the following output.\r\n" ); - Console.WriteLine( formatter, "char", "byte array" ); - Console.WriteLine( formatter, "----", "----------" ); + "\nmethod generates the following output.\r\n"); + Console.WriteLine(formatter, "char", "byte array"); + Console.WriteLine(formatter, "----", "----------"); // Convert char values and display the results. - GetBytesChar( '\0' ); - GetBytesChar( ' ' ); - GetBytesChar( '*' ); - GetBytesChar( '3' ); - GetBytesChar( 'A' ); - GetBytesChar( '[' ); - GetBytesChar( 'a' ); - GetBytesChar( '{' ); + GetBytesChar('\0'); + GetBytesChar(' '); + GetBytesChar('*'); + GetBytesChar('3'); + GetBytesChar('A'); + GetBytesChar('['); + GetBytesChar('a'); + GetBytesChar('{'); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesdouble.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesdouble.cs index 0ddfc000eed..1d7f3a97732 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesdouble.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesdouble.cs @@ -7,39 +7,39 @@ class GetBytesDoubleDemo const string formatter = "{0,25:E16}{1,30}"; // Convert a double argument to a byte array and display it. - public static void GetBytesDouble( double argument ) + public static void GetBytesDouble(double argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( double ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "double", "byte array" ); - Console.WriteLine( formatter, "------", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "double", "byte array"); + Console.WriteLine(formatter, "------", "----------"); // Convert double values and display the results. - GetBytesDouble( 0.0 ); - GetBytesDouble( 1.0 ); - GetBytesDouble( 255.0 ); - GetBytesDouble( 4294967295.0 ); - GetBytesDouble( 0.00390625 ); - GetBytesDouble( 0.00000000023283064365386962890625 ); - GetBytesDouble( 1.23456789012345E-300 ); - GetBytesDouble( 1.2345678901234565 ); - GetBytesDouble( 1.2345678901234567 ); - GetBytesDouble( 1.2345678901234569 ); - GetBytesDouble( 1.23456789012345678E+300 ); - GetBytesDouble( double.MinValue ); - GetBytesDouble( double.MaxValue ); - GetBytesDouble( double.Epsilon ); - GetBytesDouble( double.NaN ); - GetBytesDouble( double.NegativeInfinity ); - GetBytesDouble( double.PositiveInfinity ); + GetBytesDouble(0.0); + GetBytesDouble(1.0); + GetBytesDouble(255.0); + GetBytesDouble(4294967295.0); + GetBytesDouble(0.00390625); + GetBytesDouble(0.00000000023283064365386962890625); + GetBytesDouble(1.23456789012345E-300); + GetBytesDouble(1.2345678901234565); + GetBytesDouble(1.2345678901234567); + GetBytesDouble(1.2345678901234569); + GetBytesDouble(1.23456789012345678E+300); + GetBytesDouble(double.MinValue); + GetBytesDouble(double.MaxValue); + GetBytesDouble(double.Epsilon); + GetBytesDouble(double.NaN); + GetBytesDouble(double.NegativeInfinity); + GetBytesDouble(double.PositiveInfinity); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesint16.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesint16.cs index 6f13d3665c4..69fe79fbc9a 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesint16.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesint16.cs @@ -7,29 +7,29 @@ class GetBytesInt16Demo const string formatter = "{0,10}{1,13}"; // Convert a short argument to a byte array and display it. - public static void GetBytesInt16( short argument ) + public static void GetBytesInt16(short argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( short ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "short", "byte array" ); - Console.WriteLine( formatter, "-----", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "short", "byte array"); + Console.WriteLine(formatter, "-----", "----------"); // Convert short values and display the results. - GetBytesInt16( 0 ); - GetBytesInt16( 15 ); - GetBytesInt16( -15 ); - GetBytesInt16( 10000 ); - GetBytesInt16( -10000 ); - GetBytesInt16( short.MinValue ); - GetBytesInt16( short.MaxValue ); + GetBytesInt16(0); + GetBytesInt16(15); + GetBytesInt16(-15); + GetBytesInt16(10000); + GetBytesInt16(-10000); + GetBytesInt16(short.MinValue); + GetBytesInt16(short.MaxValue); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesint32.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesint32.cs index 7fa605037e1..25df981a8ee 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesint32.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesint32.cs @@ -3,22 +3,19 @@ class Example { - public static void Main( ) + public static void Main() { // Define an array of integers. int[] values = { 0, 15, -15, 0x100000, -0x100000, 1000000000, -1000000000, int.MinValue, int.MaxValue }; // Convert each integer to a byte array. - Console.WriteLine("{0,16}{1,10}{2,17}", "Integer", - "Endian", "Byte Array"); - Console.WriteLine("{0,16}{1,10}{2,17}", "---", "------", - "----------" ); - foreach (var value in values) { - byte[] byteArray = BitConverter.GetBytes(value); - Console.WriteLine("{0,16}{1,10}{2,17}", value, - BitConverter.IsLittleEndian ? "Little" : " Big", - BitConverter.ToString(byteArray)); + Console.WriteLine($"{"Integer",16}{"Endian",10}{"Byte Array",17}"); + Console.WriteLine($"{"---",16}{"------",10}{"----------",17}"); + foreach (int value in values) + { + byte[] byteArray = BitConverter.GetBytes(value); + Console.WriteLine($"{value,16}{(BitConverter.IsLittleEndian ? "Little" : " Big"),10}{BitConverter.ToString(byteArray),17}"); } } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesint64.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesint64.cs index 9a4ed122d81..98b488edcde 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesint64.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesint64.cs @@ -12,16 +12,15 @@ public static void Main() -1000000000000000000, long.MinValue, long.MaxValue }; - Console.WriteLine( "{0,22}{1,10} {2,30}", "Int64", "Endian", "Byte Array"); - Console.WriteLine( "{0,22}{1,10} {2,30}", "----", "------", "----------" ); + Console.WriteLine($"{"Int64",22}{"Endian",10} {"Byte Array",30}"); + Console.WriteLine($"{"----",22}{"------",10} {"----------",30}"); - foreach (var value in values) { + foreach (long value in values) + { // Convert each Int64 value to a byte array. byte[] byteArray = BitConverter.GetBytes(value); // Display the result. - Console.WriteLine("{0,22}{1,10}{2,30}", value, - BitConverter.IsLittleEndian ? "Little" : "Big", - BitConverter.ToString(byteArray)); + Console.WriteLine($"{value,22}{(BitConverter.IsLittleEndian ? "Little" : "Big"),10}{BitConverter.ToString(byteArray),30}"); } } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytessingle.cs b/snippets/csharp/System/BitConverter/GetBytes/bytessingle.cs index 9c0df0f1d3a..0b476d52251 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytessingle.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytessingle.cs @@ -7,39 +7,39 @@ class GetBytesSingleDemo const string formatter = "{0,16:E7}{1,20}"; // Convert a float argument to a byte array and display it. - public static void GetBytesSingle( float argument ) + public static void GetBytesSingle(float argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( float ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "float", "byte array" ); - Console.WriteLine( formatter, "-----", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "float", "byte array"); + Console.WriteLine(formatter, "-----", "----------"); // Convert float values and display the results. - GetBytesSingle( 0.0F ); - GetBytesSingle( 1.0F ); - GetBytesSingle( 15.0F ); - GetBytesSingle( 65535.0F ); - GetBytesSingle( 0.00390625F ); - GetBytesSingle( 0.00000000023283064365386962890625F ); - GetBytesSingle( 1.2345E-35F ); - GetBytesSingle( 1.2345671F ); - GetBytesSingle( 1.2345673F ); - GetBytesSingle( 1.2345677F ); - GetBytesSingle( 1.23456789E+35F ); - GetBytesSingle( float.MinValue ); - GetBytesSingle( float.MaxValue ); - GetBytesSingle( float.Epsilon ); - GetBytesSingle( float.NaN ); - GetBytesSingle( float.NegativeInfinity ); - GetBytesSingle( float.PositiveInfinity ); + GetBytesSingle(0.0F); + GetBytesSingle(1.0F); + GetBytesSingle(15.0F); + GetBytesSingle(65535.0F); + GetBytesSingle(0.00390625F); + GetBytesSingle(0.00000000023283064365386962890625F); + GetBytesSingle(1.2345E-35F); + GetBytesSingle(1.2345671F); + GetBytesSingle(1.2345673F); + GetBytesSingle(1.2345677F); + GetBytesSingle(1.23456789E+35F); + GetBytesSingle(float.MinValue); + GetBytesSingle(float.MaxValue); + GetBytesSingle(float.Epsilon); + GetBytesSingle(float.NaN); + GetBytesSingle(float.NegativeInfinity); + GetBytesSingle(float.PositiveInfinity); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesuint16.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesuint16.cs index d6801327ac7..cfa9dd24e5f 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesuint16.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesuint16.cs @@ -7,28 +7,28 @@ class GetBytesUInt16Demo const string formatter = "{0,10}{1,13}"; // Convert a ushort argument to a byte array and display it. - public static void GetBytesUInt16( ushort argument ) + public static void GetBytesUInt16(ushort argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( ushort ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "ushort", "byte array" ); - Console.WriteLine( formatter, "------", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "ushort", "byte array"); + Console.WriteLine(formatter, "------", "----------"); // Convert ushort values and display the results. - GetBytesUInt16( 15 ); - GetBytesUInt16( 1023 ); - GetBytesUInt16( 10000 ); - GetBytesUInt16( ushort.MinValue ); - GetBytesUInt16( (ushort)short.MaxValue ); - GetBytesUInt16( ushort.MaxValue ); + GetBytesUInt16(15); + GetBytesUInt16(1023); + GetBytesUInt16(10000); + GetBytesUInt16(ushort.MinValue); + GetBytesUInt16((ushort)short.MaxValue); + GetBytesUInt16(ushort.MaxValue); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesuint32.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesuint32.cs index e4e0fd4af08..3d031a84c25 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesuint32.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesuint32.cs @@ -7,29 +7,29 @@ class GetBytesUInt32Demo const string formatter = "{0,16}{1,20}"; // Convert a uint argument to a byte array and display it. - public static void GetBytesUInt32( uint argument ) + public static void GetBytesUInt32(uint argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( uint ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "uint", "byte array" ); - Console.WriteLine( formatter, "----", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "uint", "byte array"); + Console.WriteLine(formatter, "----", "----------"); // Convert uint values and display the results. - GetBytesUInt32( 15 ); - GetBytesUInt32( 1023 ); - GetBytesUInt32( 0x100000 ); - GetBytesUInt32( 1000000000 ); - GetBytesUInt32( uint.MinValue ); - GetBytesUInt32( int.MaxValue ); - GetBytesUInt32( uint.MaxValue ); + GetBytesUInt32(15); + GetBytesUInt32(1023); + GetBytesUInt32(0x100000); + GetBytesUInt32(1000000000); + GetBytesUInt32(uint.MinValue); + GetBytesUInt32(int.MaxValue); + GetBytesUInt32(uint.MaxValue); } } diff --git a/snippets/csharp/System/BitConverter/GetBytes/bytesuint64.cs b/snippets/csharp/System/BitConverter/GetBytes/bytesuint64.cs index ba9ede9adc3..105fba08017 100644 --- a/snippets/csharp/System/BitConverter/GetBytes/bytesuint64.cs +++ b/snippets/csharp/System/BitConverter/GetBytes/bytesuint64.cs @@ -7,31 +7,31 @@ class GetBytesUInt64Demo const string formatter = "{0,22}{1,30}"; // Convert a ulong argument to a byte array and display it. - public static void GetBytesUInt64( ulong argument ) + public static void GetBytesUInt64(ulong argument) { - byte[ ] byteArray = BitConverter.GetBytes( argument ); - Console.WriteLine( formatter, argument, - BitConverter.ToString( byteArray ) ); + byte[] byteArray = BitConverter.GetBytes(argument); + Console.WriteLine(formatter, argument, + BitConverter.ToString(byteArray)); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.GetBytes( ulong ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "ulong", "byte array" ); - Console.WriteLine( formatter, "-----", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "ulong", "byte array"); + Console.WriteLine(formatter, "-----", "----------"); // Convert ulong values and display the results. - GetBytesUInt64( 0xFFFFFF ); - GetBytesUInt64( 1000000000 ); - GetBytesUInt64( 0x100000000 ); - GetBytesUInt64( 0xAAAAAAAAAAAA ); - GetBytesUInt64( 1000000000000000000 ); - GetBytesUInt64( 10000000000000000000 ); - GetBytesUInt64( ulong.MinValue ); - GetBytesUInt64( long.MaxValue ); - GetBytesUInt64( ulong.MaxValue ); + GetBytesUInt64(0xFFFFFF); + GetBytesUInt64(1000000000); + GetBytesUInt64(0x100000000); + GetBytesUInt64(0xAAAAAAAAAAAA); + GetBytesUInt64(1000000000000000000); + GetBytesUInt64(10000000000000000000); + GetBytesUInt64(ulong.MinValue); + GetBytesUInt64(long.MaxValue); + GetBytesUInt64(ulong.MaxValue); } } diff --git a/snippets/csharp/System/BitConverter/Overview/bitconv.cs b/snippets/csharp/System/BitConverter/Overview/bitconv.cs index 033e95b0488..69926f0a1cd 100644 --- a/snippets/csharp/System/BitConverter/Overview/bitconv.cs +++ b/snippets/csharp/System/BitConverter/Overview/bitconv.cs @@ -4,39 +4,39 @@ class BitConverterDemo { - public static void Main( ) + public static void Main() { const string formatter = "{0,25}{1,30}"; - double aDoubl = 0.1111111111111111111; - float aSingl = 0.1111111111111111111F; - long aLong = 1111111111111111111; - int anInt = 1111111111; - short aShort = 11111; - char aChar = '*'; - bool aBool = true; + double aDoubl = 0.1111111111111111111; + float aSingl = 0.1111111111111111111F; + long aLong = 1111111111111111111; + int anInt = 1111111111; + short aShort = 11111; + char aChar = '*'; + bool aBool = true; Console.WriteLine( "This example of methods of the BitConverter class" + - "\ngenerates the following output.\n" ); - Console.WriteLine( formatter, "argument", "byte array" ); - Console.WriteLine( formatter, "--------", "----------" ); + "\ngenerates the following output.\n"); + Console.WriteLine(formatter, "argument", "byte array"); + Console.WriteLine(formatter, "--------", "----------"); // Convert values to Byte arrays and display them. - Console.WriteLine( formatter, aDoubl, - BitConverter.ToString( BitConverter.GetBytes( aDoubl ) ) ); - Console.WriteLine( formatter, aSingl, - BitConverter.ToString( BitConverter.GetBytes( aSingl ) ) ); - Console.WriteLine( formatter, aLong, - BitConverter.ToString( BitConverter.GetBytes( aLong ) ) ); - Console.WriteLine( formatter, anInt, - BitConverter.ToString( BitConverter.GetBytes( anInt ) ) ); - Console.WriteLine( formatter, aShort, - BitConverter.ToString( BitConverter.GetBytes( aShort ) ) ); - Console.WriteLine( formatter, aChar, - BitConverter.ToString( BitConverter.GetBytes( aChar ) ) ); - Console.WriteLine( formatter, aBool, - BitConverter.ToString( BitConverter.GetBytes( aBool ) ) ); + Console.WriteLine(formatter, aDoubl, + BitConverter.ToString(BitConverter.GetBytes(aDoubl))); + Console.WriteLine(formatter, aSingl, + BitConverter.ToString(BitConverter.GetBytes(aSingl))); + Console.WriteLine(formatter, aLong, + BitConverter.ToString(BitConverter.GetBytes(aLong))); + Console.WriteLine(formatter, anInt, + BitConverter.ToString(BitConverter.GetBytes(anInt))); + Console.WriteLine(formatter, aShort, + BitConverter.ToString(BitConverter.GetBytes(aShort))); + Console.WriteLine(formatter, aChar, + BitConverter.ToString(BitConverter.GetBytes(aChar))); + Console.WriteLine(formatter, aBool, + BitConverter.ToString(BitConverter.GetBytes(aBool))); } } diff --git a/snippets/csharp/System/BitConverter/Overview/example1.cs b/snippets/csharp/System/BitConverter/Overview/example1.cs index ca9d6d590c1..9dc71777abc 100644 --- a/snippets/csharp/System/BitConverter/Overview/example1.cs +++ b/snippets/csharp/System/BitConverter/Overview/example1.cs @@ -1,23 +1,20 @@ -// +// using System; public class Example { - public static void Main() - { - int value = -16; - Byte[] bytes = BitConverter.GetBytes(value); + public static void Main() + { + int value = -16; + byte[] bytes = BitConverter.GetBytes(value); - // Convert bytes back to int. - int intValue = BitConverter.ToInt32(bytes, 0); - Console.WriteLine("{0} = {1}: {2}", - value, intValue, - value.Equals(intValue) ? "Round-trips" : "Does not round-trip"); - // Convert bytes to UInt32. - uint uintValue = BitConverter.ToUInt32(bytes, 0); - Console.WriteLine("{0} = {1}: {2}", value, uintValue, - value.Equals(uintValue) ? "Round-trips" : "Does not round-trip"); - } + // Convert bytes back to int. + int intValue = BitConverter.ToInt32(bytes, 0); + Console.WriteLine($"{value} = {intValue}: {(value.Equals(intValue) ? "Round-trips" : "Does not round-trip")}"); + // Convert bytes to UInt32. + uint uintValue = BitConverter.ToUInt32(bytes, 0); + Console.WriteLine($"{value} = {uintValue}: {(value.Equals(uintValue) ? "Round-trips" : "Does not round-trip")}"); + } } // The example displays the following output: // -16 = -16: Round-trips diff --git a/snippets/csharp/System/BitConverter/Overview/littleend.cs b/snippets/csharp/System/BitConverter/Overview/littleend.cs index dab9c37ad0b..395983be475 100644 --- a/snippets/csharp/System/BitConverter/Overview/littleend.cs +++ b/snippets/csharp/System/BitConverter/Overview/littleend.cs @@ -4,14 +4,13 @@ class LittleEndDemo { - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the BitConverter.IsLittleEndian field " + "generates \nthe following output when run on " + "x86-class computers.\n"); - Console.WriteLine( "IsLittleEndian: {0}", - BitConverter.IsLittleEndian ); + Console.WriteLine($"IsLittleEndian: {BitConverter.IsLittleEndian}"); } } diff --git a/snippets/csharp/System/BitConverter/Overview/networkorder1.cs b/snippets/csharp/System/BitConverter/Overview/networkorder1.cs index b3d387d6747..58bc33ec7fa 100644 --- a/snippets/csharp/System/BitConverter/Overview/networkorder1.cs +++ b/snippets/csharp/System/BitConverter/Overview/networkorder1.cs @@ -3,28 +3,28 @@ public class Example { - public static void Main() - { - int value = 12345678; - byte[] bytes = BitConverter.GetBytes(value); - Console.WriteLine(BitConverter.ToString(bytes)); + public static void Main() + { + int value = 12345678; + byte[] bytes = BitConverter.GetBytes(value); + Console.WriteLine(BitConverter.ToString(bytes)); - if (BitConverter.IsLittleEndian) - Array.Reverse(bytes); + if (BitConverter.IsLittleEndian) + Array.Reverse(bytes); - Console.WriteLine(BitConverter.ToString(bytes)); - // Call method to send byte stream across machine boundaries. + Console.WriteLine(BitConverter.ToString(bytes)); + // Call method to send byte stream across machine boundaries. - // Receive byte stream from beyond machine boundaries. - Console.WriteLine(BitConverter.ToString(bytes)); - if (BitConverter.IsLittleEndian) - Array.Reverse(bytes); + // Receive byte stream from beyond machine boundaries. + Console.WriteLine(BitConverter.ToString(bytes)); + if (BitConverter.IsLittleEndian) + Array.Reverse(bytes); - Console.WriteLine(BitConverter.ToString(bytes)); - int result = BitConverter.ToInt32(bytes, 0); - Console.WriteLine("Original value: {0}", value); - Console.WriteLine("Returned value: {0}", result); - } + Console.WriteLine(BitConverter.ToString(bytes)); + int result = BitConverter.ToInt32(bytes, 0); + Console.WriteLine($"Original value: {value}"); + Console.WriteLine($"Returned value: {result}"); + } } // The example displays the following output on a little-endian system: // 4E-61-BC-00 diff --git a/snippets/csharp/System/BitConverter/ToBoolean/batobool.cs b/snippets/csharp/System/BitConverter/ToBoolean/batobool.cs index b9c0c2cc062..aad6bd119c6 100644 --- a/snippets/csharp/System/BitConverter/ToBoolean/batobool.cs +++ b/snippets/csharp/System/BitConverter/ToBoolean/batobool.cs @@ -3,16 +3,15 @@ class Example { - public static void Main( ) + public static void Main() { // Define an array of byte values. byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64, 128, 255 }; - Console.WriteLine("{0,5}{1,16}{2,10}\n", "index", "array element", "bool" ); + Console.WriteLine($"{"index",5}{"array element",16}{"bool",10}\n"); // Convert each array element to a Boolean value. for (int index = 0; index < bytes.Length; index++) - Console.WriteLine("{0,5}{1,16:X2}{2,10}", index, bytes[index], - BitConverter.ToBoolean(bytes, index)); + Console.WriteLine($"{index,5}{bytes[index],16:X2}{BitConverter.ToBoolean(bytes, index),10}"); } } // The example displays the following output: diff --git a/snippets/csharp/System/BitConverter/ToBoolean/batochar.cs b/snippets/csharp/System/BitConverter/ToBoolean/batochar.cs index 84a783e839e..4e9df243afc 100644 --- a/snippets/csharp/System/BitConverter/ToBoolean/batochar.cs +++ b/snippets/csharp/System/BitConverter/ToBoolean/batochar.cs @@ -7,15 +7,15 @@ class BytesToCharDemo const string formatter = "{0,5}{1,17}{2,8}"; // Convert two byte array elements to a char and display it. - public static void BAToChar( byte[] bytes, int index ) + public static void BAToChar(byte[] bytes, int index) { - char value = BitConverter.ToChar( bytes, index ); + char value = BitConverter.ToChar(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 2 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 2), value); } - public static void Main( ) + public static void Main() { byte[] byteArray = { 32, 0, 0, 42, 0, 65, 0, 125, 0, @@ -24,24 +24,24 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToChar( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts \nelements of a byte array to char values.\n" ); - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); - Console.WriteLine( BitConverter.ToString( byteArray ) ); - Console.WriteLine( ); - Console.WriteLine( formatter, "index", "array elements", "char" ); - Console.WriteLine( formatter, "-----", "--------------", "----" ); + "converts \nelements of a byte array to char values.\n"); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); + Console.WriteLine(BitConverter.ToString(byteArray)); + Console.WriteLine(); + Console.WriteLine(formatter, "index", "array elements", "char"); + Console.WriteLine(formatter, "-----", "--------------", "----"); // Convert byte array elements to char values. - BAToChar( byteArray, 0 ); - BAToChar( byteArray, 1 ); - BAToChar( byteArray, 3 ); - BAToChar( byteArray, 5 ); - BAToChar( byteArray, 7 ); - BAToChar( byteArray, 9 ); - BAToChar( byteArray, 11 ); - BAToChar( byteArray, 13 ); - BAToChar( byteArray, 15 ); + BAToChar(byteArray, 0); + BAToChar(byteArray, 1); + BAToChar(byteArray, 3); + BAToChar(byteArray, 5); + BAToChar(byteArray, 7); + BAToChar(byteArray, 9); + BAToChar(byteArray, 11); + BAToChar(byteArray, 13); + BAToChar(byteArray, 15); } } diff --git a/snippets/csharp/System/BitConverter/ToBoolean/batodouble.cs b/snippets/csharp/System/BitConverter/ToBoolean/batodouble.cs index 44ea00d91a4..52abb59c01c 100644 --- a/snippets/csharp/System/BitConverter/ToBoolean/batodouble.cs +++ b/snippets/csharp/System/BitConverter/ToBoolean/batodouble.cs @@ -7,37 +7,37 @@ class BytesToDoubleDemo const string formatter = "{0,5}{1,27}{2,27:E16}"; // Convert eight byte array elements to a double and display it. - public static void BAToDouble( byte[ ] bytes, int index ) + public static void BAToDouble(byte[] bytes, int index) { - double value = BitConverter.ToDouble( bytes, index ); + double value = BitConverter.ToDouble(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 8 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 8), value); } // Display a byte array, using multiple lines if necessary. - public static void WriteMultiLineByteArray( byte[ ] bytes ) + public static void WriteMultiLineByteArray(byte[] bytes) { const int rowSize = 20; int iter; - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); - for( iter = 0; iter < bytes.Length - rowSize; iter += rowSize ) + for (iter = 0; iter < bytes.Length - rowSize; iter += rowSize) { Console.Write( - BitConverter.ToString( bytes, iter, rowSize ) ); - Console.WriteLine( "-" ); + BitConverter.ToString(bytes, iter, rowSize)); + Console.WriteLine("-"); } - Console.WriteLine( BitConverter.ToString( bytes, iter ) ); - Console.WriteLine( ); + Console.WriteLine(BitConverter.ToString(bytes, iter)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = { + byte[] byteArray = { 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 224, 111, 64, 0, 0, 224, 255, 255, 255, 239, 65, 0, 0, 0, 0, @@ -55,33 +55,33 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToDouble( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to double values.\n" ); + "converts elements \nof a byte array to double values.\n"); - WriteMultiLineByteArray( byteArray ); + WriteMultiLineByteArray(byteArray); - Console.WriteLine( formatter, "index", "array elements", - "double" ); - Console.WriteLine( formatter, "-----", "--------------", - "------" ); + Console.WriteLine(formatter, "index", "array elements", + "double"); + Console.WriteLine(formatter, "-----", "--------------", + "------"); // Convert byte array elements to double values. - BAToDouble( byteArray, 0 ); - BAToDouble( byteArray, 2 ); - BAToDouble( byteArray, 10 ); - BAToDouble( byteArray, 18 ); - BAToDouble( byteArray, 26 ); - BAToDouble( byteArray, 34 ); - BAToDouble( byteArray, 42 ); - BAToDouble( byteArray, 50 ); - BAToDouble( byteArray, 58 ); - BAToDouble( byteArray, 66 ); - BAToDouble( byteArray, 74 ); - BAToDouble( byteArray, 82 ); - BAToDouble( byteArray, 89 ); - BAToDouble( byteArray, 97 ); - BAToDouble( byteArray, 99 ); - BAToDouble( byteArray, 107 ); - BAToDouble( byteArray, 115 ); + BAToDouble(byteArray, 0); + BAToDouble(byteArray, 2); + BAToDouble(byteArray, 10); + BAToDouble(byteArray, 18); + BAToDouble(byteArray, 26); + BAToDouble(byteArray, 34); + BAToDouble(byteArray, 42); + BAToDouble(byteArray, 50); + BAToDouble(byteArray, 58); + BAToDouble(byteArray, 66); + BAToDouble(byteArray, 74); + BAToDouble(byteArray, 82); + BAToDouble(byteArray, 89); + BAToDouble(byteArray, 97); + BAToDouble(byteArray, 99); + BAToDouble(byteArray, 107); + BAToDouble(byteArray, 115); } } diff --git a/snippets/csharp/System/BitConverter/ToBoolean/batosingle.cs b/snippets/csharp/System/BitConverter/ToBoolean/batosingle.cs index 4f76dd0305f..345e6005795 100644 --- a/snippets/csharp/System/BitConverter/ToBoolean/batosingle.cs +++ b/snippets/csharp/System/BitConverter/ToBoolean/batosingle.cs @@ -7,37 +7,37 @@ class BytesToSingleDemo const string formatter = "{0,5}{1,17}{2,18:E7}"; // Convert four byte array elements to a float and display it. - public static void BAToSingle( byte[ ] bytes, int index ) + public static void BAToSingle(byte[] bytes, int index) { - float value = BitConverter.ToSingle( bytes, index ); + float value = BitConverter.ToSingle(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 4 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 4), value); } // Display a byte array, using multiple lines if necessary. - public static void WriteMultiLineByteArray( byte[ ] bytes ) + public static void WriteMultiLineByteArray(byte[] bytes) { const int rowSize = 20; int iter; - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); - for( iter = 0; iter < bytes.Length - rowSize; iter += rowSize ) + for (iter = 0; iter < bytes.Length - rowSize; iter += rowSize) { Console.Write( - BitConverter.ToString( bytes, iter, rowSize ) ); - Console.WriteLine( "-" ); + BitConverter.ToString(bytes, iter, rowSize)); + Console.WriteLine("-"); } - Console.WriteLine( BitConverter.ToString( bytes, iter ) ); - Console.WriteLine( ); + Console.WriteLine(BitConverter.ToString(bytes, iter)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = { + byte[] byteArray = { 0, 0, 0, 0, 128, 63, 0, 0, 112, 65, 0, 255, 127, 71, 0, 0, 128, 59, 0, 0, 128, 47, 73, 70, 131, 5, 75, 6, 158, 63, @@ -49,33 +49,33 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToSingle( byte( ), " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to float values.\n" ); + "converts elements \nof a byte array to float values.\n"); - WriteMultiLineByteArray( byteArray ); + WriteMultiLineByteArray(byteArray); - Console.WriteLine( formatter, "index", "array elements", - "float" ); - Console.WriteLine( formatter, "-----", "--------------", - "-----" ); + Console.WriteLine(formatter, "index", "array elements", + "float"); + Console.WriteLine(formatter, "-----", "--------------", + "-----"); // Convert byte array elements to float values. - BAToSingle( byteArray, 0 ); - BAToSingle( byteArray, 2 ); - BAToSingle( byteArray, 6 ); - BAToSingle( byteArray, 10 ); - BAToSingle( byteArray, 14 ); - BAToSingle( byteArray, 18 ); - BAToSingle( byteArray, 22 ); - BAToSingle( byteArray, 26 ); - BAToSingle( byteArray, 30 ); - BAToSingle( byteArray, 34 ); - BAToSingle( byteArray, 38 ); - BAToSingle( byteArray, 42 ); - BAToSingle( byteArray, 45 ); - BAToSingle( byteArray, 49 ); - BAToSingle( byteArray, 51 ); - BAToSingle( byteArray, 55 ); - BAToSingle( byteArray, 59 ); + BAToSingle(byteArray, 0); + BAToSingle(byteArray, 2); + BAToSingle(byteArray, 6); + BAToSingle(byteArray, 10); + BAToSingle(byteArray, 14); + BAToSingle(byteArray, 18); + BAToSingle(byteArray, 22); + BAToSingle(byteArray, 26); + BAToSingle(byteArray, 30); + BAToSingle(byteArray, 34); + BAToSingle(byteArray, 38); + BAToSingle(byteArray, 42); + BAToSingle(byteArray, 45); + BAToSingle(byteArray, 49); + BAToSingle(byteArray, 51); + BAToSingle(byteArray, 55); + BAToSingle(byteArray, 59); } } diff --git a/snippets/csharp/System/BitConverter/ToInt16/batoint16.cs b/snippets/csharp/System/BitConverter/ToInt16/batoint16.cs index 52b90dbe0bd..a843ed76434 100644 --- a/snippets/csharp/System/BitConverter/ToInt16/batoint16.cs +++ b/snippets/csharp/System/BitConverter/ToInt16/batoint16.cs @@ -7,38 +7,38 @@ class BytesToInt16Demo const string formatter = "{0,5}{1,17}{2,10}"; // Convert two byte array elements to a short and display it. - public static void BAToInt16( byte[ ] bytes, int index ) + public static void BAToInt16(byte[] bytes, int index) { - short value = BitConverter.ToInt16( bytes, index ); + short value = BitConverter.ToInt16(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 2 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 2), value); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = + byte[] byteArray = { 15, 0, 0, 128, 16, 39, 240, 216, 241, 255, 127 }; Console.WriteLine( "This example of the BitConverter.ToInt16( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to short values.\n" ); - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); - Console.WriteLine( BitConverter.ToString( byteArray ) ); - Console.WriteLine( ); - Console.WriteLine( formatter, "index", "array elements", "short" ); - Console.WriteLine( formatter, "-----", "--------------", "-----" ); + "converts elements \nof a byte array to short values.\n"); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); + Console.WriteLine(BitConverter.ToString(byteArray)); + Console.WriteLine(); + Console.WriteLine(formatter, "index", "array elements", "short"); + Console.WriteLine(formatter, "-----", "--------------", "-----"); // Convert byte array elements to short values. - BAToInt16( byteArray, 1 ); - BAToInt16( byteArray, 0 ); - BAToInt16( byteArray, 8 ); - BAToInt16( byteArray, 4 ); - BAToInt16( byteArray, 6 ); - BAToInt16( byteArray, 9 ); - BAToInt16( byteArray, 2 ); + BAToInt16(byteArray, 1); + BAToInt16(byteArray, 0); + BAToInt16(byteArray, 8); + BAToInt16(byteArray, 4); + BAToInt16(byteArray, 6); + BAToInt16(byteArray, 9); + BAToInt16(byteArray, 2); } } diff --git a/snippets/csharp/System/BitConverter/ToInt16/batoint32.cs b/snippets/csharp/System/BitConverter/ToInt16/batoint32.cs index 63bf8aef286..b986a064670 100644 --- a/snippets/csharp/System/BitConverter/ToInt16/batoint32.cs +++ b/snippets/csharp/System/BitConverter/ToInt16/batoint32.cs @@ -7,37 +7,37 @@ class BytesToInt32Demo const string formatter = "{0,5}{1,17}{2,15}"; // Convert four byte array elements to an int and display it. - public static void BAToInt32( byte[ ] bytes, int index ) + public static void BAToInt32(byte[] bytes, int index) { - int value = BitConverter.ToInt32( bytes, index ); + int value = BitConverter.ToInt32(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 4 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 4), value); } // Display a byte array, using multiple lines if necessary. - public static void WriteMultiLineByteArray( byte[ ] bytes ) + public static void WriteMultiLineByteArray(byte[] bytes) { const int rowSize = 20; int iter; - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); - for( iter = 0; iter < bytes.Length - rowSize; iter += rowSize ) + for (iter = 0; iter < bytes.Length - rowSize; iter += rowSize) { Console.Write( - BitConverter.ToString( bytes, iter, rowSize ) ); - Console.WriteLine( "-" ); + BitConverter.ToString(bytes, iter, rowSize)); + Console.WriteLine("-"); } - Console.WriteLine( BitConverter.ToString( bytes, iter ) ); - Console.WriteLine( ); + Console.WriteLine(BitConverter.ToString(bytes, iter)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = { + byte[] byteArray = { 15, 0, 0, 0, 0, 128, 0, 0, 16, 0, 0, 240, 255, 0, 202, 154, 59, 0, 54, 101, 196, 241, 255, 255, 255, 127 }; @@ -45,25 +45,25 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToInt32( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to int values.\n" ); + "converts elements \nof a byte array to int values.\n"); - WriteMultiLineByteArray( byteArray ); + WriteMultiLineByteArray(byteArray); - Console.WriteLine( formatter, "index", "array elements", - "int" ); - Console.WriteLine( formatter, "-----", "--------------", - "---" ); + Console.WriteLine(formatter, "index", "array elements", + "int"); + Console.WriteLine(formatter, "-----", "--------------", + "---"); // Convert byte array elements to int values. - BAToInt32( byteArray, 1 ); - BAToInt32( byteArray, 0 ); - BAToInt32( byteArray, 21 ); - BAToInt32( byteArray, 6 ); - BAToInt32( byteArray, 9 ); - BAToInt32( byteArray, 13 ); - BAToInt32( byteArray, 17 ); - BAToInt32( byteArray, 22 ); - BAToInt32( byteArray, 2 ); + BAToInt32(byteArray, 1); + BAToInt32(byteArray, 0); + BAToInt32(byteArray, 21); + BAToInt32(byteArray, 6); + BAToInt32(byteArray, 9); + BAToInt32(byteArray, 13); + BAToInt32(byteArray, 17); + BAToInt32(byteArray, 22); + BAToInt32(byteArray, 2); } } diff --git a/snippets/csharp/System/BitConverter/ToInt16/batoint64.cs b/snippets/csharp/System/BitConverter/ToInt16/batoint64.cs index 25a977b4bf7..7e9d4642449 100644 --- a/snippets/csharp/System/BitConverter/ToInt16/batoint64.cs +++ b/snippets/csharp/System/BitConverter/ToInt16/batoint64.cs @@ -7,37 +7,37 @@ class BytesToInt64Demo const string formatter = "{0,5}{1,27}{2,24}"; // Convert eight byte array elements to a long and display it. - public static void BAToInt64( byte[ ] bytes, int index ) + public static void BAToInt64(byte[] bytes, int index) { - long value = BitConverter.ToInt64( bytes, index ); + long value = BitConverter.ToInt64(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 8 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 8), value); } // Display a byte array, using multiple lines if necessary. - public static void WriteMultiLineByteArray( byte[ ] bytes ) + public static void WriteMultiLineByteArray(byte[] bytes) { const int rowSize = 20; int iter; - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); - for( iter = 0; iter < bytes.Length - rowSize; iter += rowSize ) + for (iter = 0; iter < bytes.Length - rowSize; iter += rowSize) { Console.Write( - BitConverter.ToString( bytes, iter, rowSize ) ); - Console.WriteLine( "-" ); + BitConverter.ToString(bytes, iter, rowSize)); + Console.WriteLine("-"); } - Console.WriteLine( BitConverter.ToString( bytes, iter ) ); - Console.WriteLine( ); + Console.WriteLine(BitConverter.ToString(bytes, iter)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = { + byte[] byteArray = { 0, 54, 101, 196, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 202, 154, 59, 0, 0, 0, 0, 1, 0, 0, 0, 0, @@ -50,27 +50,27 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToInt64( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to long values.\r\n" ); + "converts elements \nof a byte array to long values.\r\n"); - WriteMultiLineByteArray( byteArray ); + WriteMultiLineByteArray(byteArray); - Console.WriteLine( formatter, "index", "array elements", "long" ); - Console.WriteLine( formatter, "-----", "--------------", "----" ); + Console.WriteLine(formatter, "index", "array elements", "long"); + Console.WriteLine(formatter, "-----", "--------------", "----"); // Convert byte array elements to long values. - BAToInt64( byteArray, 8 ); - BAToInt64( byteArray, 5 ); - BAToInt64( byteArray, 34 ); - BAToInt64( byteArray, 17 ); - BAToInt64( byteArray, 0 ); - BAToInt64( byteArray, 21 ); - BAToInt64( byteArray, 26 ); - BAToInt64( byteArray, 53 ); - BAToInt64( byteArray, 45 ); - BAToInt64( byteArray, 59 ); - BAToInt64( byteArray, 67 ); - BAToInt64( byteArray, 37 ); - BAToInt64( byteArray, 9 ); + BAToInt64(byteArray, 8); + BAToInt64(byteArray, 5); + BAToInt64(byteArray, 34); + BAToInt64(byteArray, 17); + BAToInt64(byteArray, 0); + BAToInt64(byteArray, 21); + BAToInt64(byteArray, 26); + BAToInt64(byteArray, 53); + BAToInt64(byteArray, 45); + BAToInt64(byteArray, 59); + BAToInt64(byteArray, 67); + BAToInt64(byteArray, 37); + BAToInt64(byteArray, 9); } } diff --git a/snippets/csharp/System/BitConverter/ToInt32/toint32.cs b/snippets/csharp/System/BitConverter/ToInt32/toint32.cs index 5b8167924e7..dd980241502 100644 --- a/snippets/csharp/System/BitConverter/ToInt32/toint32.cs +++ b/snippets/csharp/System/BitConverter/ToInt32/toint32.cs @@ -1,35 +1,35 @@ -// +// using System; public class Example { - public static void Main() - { - // Create an Integer from a 4-byte array. - Byte[] bytes1 = { 0xEC, 0x00, 0x00, 0x00 }; - Console.WriteLine("{0}--> 0x{1:X4} ({1:N0})", FormatBytes(bytes1), - BitConverter.ToInt32(bytes1, 0)); - // Create an Integer from the upper four bytes of a byte array. - Byte[] bytes2 = BitConverter.GetBytes(Int64.MaxValue / 2); - Console.WriteLine("{0}--> 0x{1:X4} ({1:N0})", FormatBytes(bytes2), - BitConverter.ToInt32(bytes2, 4)); + public static void Main() + { + // Create an Integer from a 4-byte array. + byte[] bytes1 = { 0xEC, 0x00, 0x00, 0x00 }; + Console.WriteLine("{0}--> 0x{1:X4} ({1:N0})", FormatBytes(bytes1), + BitConverter.ToInt32(bytes1, 0)); + // Create an Integer from the upper four bytes of a byte array. + byte[] bytes2 = BitConverter.GetBytes(long.MaxValue / 2); + Console.WriteLine("{0}--> 0x{1:X4} ({1:N0})", FormatBytes(bytes2), + BitConverter.ToInt32(bytes2, 4)); - // Round-trip an integer value. - int original = (int) Math.Pow(16, 3); - Byte[] bytes3 = BitConverter.GetBytes(original); - int restored = BitConverter.ToInt32(bytes3, 0); - Console.WriteLine("0x{0:X4} ({0:N0}) --> {1} --> 0x{2:X4} ({2:N0})", original, - FormatBytes(bytes3), restored); - } + // Round-trip an integer value. + int original = (int)Math.Pow(16, 3); + byte[] bytes3 = BitConverter.GetBytes(original); + int restored = BitConverter.ToInt32(bytes3, 0); + Console.WriteLine("0x{0:X4} ({0:N0}) --> {1} --> 0x{2:X4} ({2:N0})", original, + FormatBytes(bytes3), restored); + } - private static string FormatBytes(Byte[] bytes) - { - string value = ""; - foreach (var byt in bytes) - value += string.Format("{0:X2} ", byt); + private static string FormatBytes(byte[] bytes) + { + string value = ""; + foreach (byte byt in bytes) + value += $"{byt:X2} "; - return value; - } + return value; + } } // The example displays the following output: // EC 00 00 00 --> 0x00EC (236) diff --git a/snippets/csharp/System/BitConverter/ToString/batostring.cs b/snippets/csharp/System/BitConverter/ToString/batostring.cs index 4dd3698b325..010f6c171be 100644 --- a/snippets/csharp/System/BitConverter/ToString/batostring.cs +++ b/snippets/csharp/System/BitConverter/ToString/batostring.cs @@ -5,42 +5,42 @@ class BytesToStringDemo { // Display a byte array with a name. - public static void WriteByteArray( byte[ ] bytes, string name ) + public static void WriteByteArray(byte[] bytes, string name) { const string underLine = "--------------------------------"; - Console.WriteLine( name ); - Console.WriteLine( underLine.Substring( 0, - Math.Min( name.Length, underLine.Length ) ) ); - Console.WriteLine( BitConverter.ToString( bytes ) ); - Console.WriteLine( ); + Console.WriteLine(name); + Console.WriteLine(underLine.Substring(0, + Math.Min(name.Length, underLine.Length))); + Console.WriteLine(BitConverter.ToString(bytes)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] arrayOne = { + byte[] arrayOne = { 0, 1, 2, 4, 8, 16, 32, 64, 128, 255 }; - byte[ ] arrayTwo = { + byte[] arrayTwo = { 32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 172, 32 }; - byte[ ] arrayThree = { + byte[] arrayThree = { 15, 0, 0, 128, 16, 39, 240, 216, 241, 255, 127 }; - byte[ ] arrayFour = { + byte[] arrayFour = { 15, 0, 0, 0, 0, 16, 0, 255, 3, 0, 0, 202, 154, 59, 255, 255, 255, 255, 127 }; - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "BitConverter.ToString( byte[ ] ) \n" + - "method generates the following output.\n" ); + "method generates the following output.\n"); - WriteByteArray( arrayOne, "arrayOne" ); - WriteByteArray( arrayTwo, "arrayTwo" ); - WriteByteArray( arrayThree, "arrayThree" ); - WriteByteArray( arrayFour, "arrayFour" ); + WriteByteArray(arrayOne, "arrayOne"); + WriteByteArray(arrayTwo, "arrayTwo"); + WriteByteArray(arrayThree, "arrayThree"); + WriteByteArray(arrayFour, "arrayFour"); } } diff --git a/snippets/csharp/System/BitConverter/ToString/batostringii.cs b/snippets/csharp/System/BitConverter/ToString/batostringii.cs index e69c5b61c09..c941ae86bee 100644 --- a/snippets/csharp/System/BitConverter/ToString/batostringii.cs +++ b/snippets/csharp/System/BitConverter/ToString/batostringii.cs @@ -5,31 +5,31 @@ class BytesToStringDemo { // Display a byte array, using multiple lines if necessary. - public static void WriteMultiLineByteArray( byte[ ] bytes, - string name ) + public static void WriteMultiLineByteArray(byte[] bytes, + string name) { const int rowSize = 20; const string underLine = "--------------------------------"; int iter; - Console.WriteLine( name ); - Console.WriteLine( underLine.Substring( 0, - Math.Min( name.Length, underLine.Length ) ) ); + Console.WriteLine(name); + Console.WriteLine(underLine.Substring(0, + Math.Min(name.Length, underLine.Length))); - for( iter = 0; iter < bytes.Length - rowSize; iter += rowSize ) + for (iter = 0; iter < bytes.Length - rowSize; iter += rowSize) { Console.Write( - BitConverter.ToString( bytes, iter, rowSize ) ); - Console.WriteLine( "-" ); + BitConverter.ToString(bytes, iter, rowSize)); + Console.WriteLine("-"); } - Console.WriteLine( BitConverter.ToString( bytes, iter ) ); - Console.WriteLine( ); + Console.WriteLine(BitConverter.ToString(bytes, iter)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] arrayOne = { + byte[] arrayOne = { 0, 0, 0, 0, 128, 63, 0, 0, 112, 65, 0, 255, 127, 71, 0, 0, 128, 59, 0, 0, 128, 47, 73, 70, 131, 5, 75, 6, 158, 63, @@ -38,7 +38,7 @@ public static void Main( ) 0, 0, 0, 192, 255, 0, 0, 128, 255, 0, 0, 128, 127 }; - byte[ ] arrayTwo = { + byte[] arrayTwo = { 255, 255, 255, 0, 0, 20, 0, 33, 0, 0, 0, 1, 0, 0, 0, 100, 167, 179, 182, 224, 13, 0, 202, 154, 59, 0, 143, 91, 0, 170, @@ -46,7 +46,7 @@ public static void Main( ) 35, 199, 138, 255, 232, 244, 255, 252, 205, 255, 255, 129 }; - byte[ ] arrayThree = { + byte[] arrayThree = { 0, 222, 0, 0, 0, 224, 111, 64, 0, 0, 224, 255, 255, 255, 239, 65, 0, 0, 131, 0, 0, 0, 112, 63, 0, 143, 0, 100, 0, 0, @@ -58,14 +58,14 @@ public static void Main( ) 0, 10, 17, 0, 0, 248, 255, 0, 88, 0, 91, 0, 0, 240, 255, 0, 0, 240, 157 }; - Console.WriteLine( "This example of the\n" + + Console.WriteLine("This example of the\n" + " BitConverter.ToString( byte[ ], int ) and \n" + " BitConverter.ToString( byte[ ], int, int ) \n" + - "methods generates the following output.\n" ); + "methods generates the following output.\n"); - WriteMultiLineByteArray( arrayOne, "arrayOne" ); - WriteMultiLineByteArray( arrayTwo, "arrayTwo" ); - WriteMultiLineByteArray( arrayThree, "arrayThree" ); + WriteMultiLineByteArray(arrayOne, "arrayOne"); + WriteMultiLineByteArray(arrayTwo, "arrayTwo"); + WriteMultiLineByteArray(arrayThree, "arrayThree"); } } diff --git a/snippets/csharp/System/BitConverter/ToUInt16/batouint16.cs b/snippets/csharp/System/BitConverter/ToUInt16/batouint16.cs index 12d2541a59a..a1d705734e4 100644 --- a/snippets/csharp/System/BitConverter/ToUInt16/batouint16.cs +++ b/snippets/csharp/System/BitConverter/ToUInt16/batouint16.cs @@ -7,15 +7,15 @@ class BytesToUInt16Demo const string formatter = "{0,5}{1,17}{2,10}"; // Convert two byte array elements to a ushort and display it. - public static void BAToUInt16( byte[ ] bytes, int index ) + public static void BAToUInt16(byte[] bytes, int index) { - ushort value = BitConverter.ToUInt16( bytes, index ); + ushort value = BitConverter.ToUInt16(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 2 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 2), value); } - public static void Main( ) + public static void Main() { byte[] byteArray = { 15, 0, 0, 255, 3, 16, 39, 255, 255, 127 }; @@ -23,23 +23,23 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToUInt16( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to ushort values.\n" ); - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); - Console.WriteLine( BitConverter.ToString( byteArray ) ); - Console.WriteLine( ); - Console.WriteLine( formatter, "index", "array elements", - "ushort" ); - Console.WriteLine( formatter, "-----", "--------------", - "------" ); + "converts elements \nof a byte array to ushort values.\n"); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); + Console.WriteLine(BitConverter.ToString(byteArray)); + Console.WriteLine(); + Console.WriteLine(formatter, "index", "array elements", + "ushort"); + Console.WriteLine(formatter, "-----", "--------------", + "------"); // Convert byte array elements to ushort values. - BAToUInt16( byteArray, 1 ); - BAToUInt16( byteArray, 0 ); - BAToUInt16( byteArray, 3 ); - BAToUInt16( byteArray, 5 ); - BAToUInt16( byteArray, 8 ); - BAToUInt16( byteArray, 7 ); + BAToUInt16(byteArray, 1); + BAToUInt16(byteArray, 0); + BAToUInt16(byteArray, 3); + BAToUInt16(byteArray, 5); + BAToUInt16(byteArray, 8); + BAToUInt16(byteArray, 7); } } diff --git a/snippets/csharp/System/BitConverter/ToUInt16/batouint32.cs b/snippets/csharp/System/BitConverter/ToUInt16/batouint32.cs index 7e04deefd1a..59c45a2b7ac 100644 --- a/snippets/csharp/System/BitConverter/ToUInt16/batouint32.cs +++ b/snippets/csharp/System/BitConverter/ToUInt16/batouint32.cs @@ -7,41 +7,41 @@ class BytesToUInt32Demo const string formatter = "{0,5}{1,17}{2,15}"; // Convert four byte array elements to a uint and display it. - public static void BAToUInt32( byte[ ] bytes, int index ) + public static void BAToUInt32(byte[] bytes, int index) { - uint value = BitConverter.ToUInt32( bytes, index ); + uint value = BitConverter.ToUInt32(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 4 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 4), value); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = { + byte[] byteArray = { 15, 0, 0, 0, 0, 16, 0, 255, 3, 0, 0, 202, 154, 59, 255, 255, 255, 255, 127 }; Console.WriteLine( "This example of the BitConverter.ToUInt32( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to uint values.\n" ); - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); - Console.WriteLine( BitConverter.ToString( byteArray ) ); - Console.WriteLine( ); - Console.WriteLine( formatter, "index", "array elements", - "uint" ); - Console.WriteLine( formatter, "-----", "--------------", - "----" ); + "converts elements \nof a byte array to uint values.\n"); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); + Console.WriteLine(BitConverter.ToString(byteArray)); + Console.WriteLine(); + Console.WriteLine(formatter, "index", "array elements", + "uint"); + Console.WriteLine(formatter, "-----", "--------------", + "----"); // Convert byte array elements to uint values. - BAToUInt32( byteArray, 1 ); - BAToUInt32( byteArray, 0 ); - BAToUInt32( byteArray, 7 ); - BAToUInt32( byteArray, 3 ); - BAToUInt32( byteArray, 10 ); - BAToUInt32( byteArray, 15 ); - BAToUInt32( byteArray, 14 ); + BAToUInt32(byteArray, 1); + BAToUInt32(byteArray, 0); + BAToUInt32(byteArray, 7); + BAToUInt32(byteArray, 3); + BAToUInt32(byteArray, 10); + BAToUInt32(byteArray, 15); + BAToUInt32(byteArray, 14); } } diff --git a/snippets/csharp/System/BitConverter/ToUInt16/batouint64.cs b/snippets/csharp/System/BitConverter/ToUInt16/batouint64.cs index a6e41e5d51a..e8573e0a4e9 100644 --- a/snippets/csharp/System/BitConverter/ToUInt16/batouint64.cs +++ b/snippets/csharp/System/BitConverter/ToUInt16/batouint64.cs @@ -7,37 +7,37 @@ class BytesToUInt64Demo const string formatter = "{0,5}{1,27}{2,24}"; // Convert eight byte array elements to a ulong and display it. - public static void BAToUInt64( byte[ ] bytes, int index ) + public static void BAToUInt64(byte[] bytes, int index) { - ulong value = BitConverter.ToUInt64( bytes, index ); + ulong value = BitConverter.ToUInt64(bytes, index); - Console.WriteLine( formatter, index, - BitConverter.ToString( bytes, index, 8 ), value ); + Console.WriteLine(formatter, index, + BitConverter.ToString(bytes, index, 8), value); } // Display a byte array, using multiple lines if necessary. - public static void WriteMultiLineByteArray( byte[ ] bytes ) + public static void WriteMultiLineByteArray(byte[] bytes) { const int rowSize = 20; int iter; - Console.WriteLine( "initial byte array" ); - Console.WriteLine( "------------------" ); + Console.WriteLine("initial byte array"); + Console.WriteLine("------------------"); - for( iter = 0; iter < bytes.Length - rowSize; iter += rowSize ) + for (iter = 0; iter < bytes.Length - rowSize; iter += rowSize) { Console.Write( - BitConverter.ToString( bytes, iter, rowSize ) ); - Console.WriteLine( "-" ); + BitConverter.ToString(bytes, iter, rowSize)); + Console.WriteLine("-"); } - Console.WriteLine( BitConverter.ToString( bytes, iter ) ); - Console.WriteLine( ); + Console.WriteLine(BitConverter.ToString(bytes, iter)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { - byte[ ] byteArray = { + byte[] byteArray = { 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 100, 167, 179, 182, 224, 13, 0, 202, 154, 59, 0, 0, 0, 0, 170, @@ -48,25 +48,25 @@ public static void Main( ) Console.WriteLine( "This example of the BitConverter.ToUInt64( byte[ ], " + "int ) \nmethod generates the following output. It " + - "converts elements \nof a byte array to ulong values.\n" ); + "converts elements \nof a byte array to ulong values.\n"); - WriteMultiLineByteArray( byteArray ); + WriteMultiLineByteArray(byteArray); - Console.WriteLine( formatter, "index", "array elements", - "ulong" ); - Console.WriteLine( formatter, "-----", "--------------", - "------" ); + Console.WriteLine(formatter, "index", "array elements", + "ulong"); + Console.WriteLine(formatter, "-----", "--------------", + "------"); // Convert byte array elements to ulong values. - BAToUInt64( byteArray, 3 ); - BAToUInt64( byteArray, 0 ); - BAToUInt64( byteArray, 21 ); - BAToUInt64( byteArray, 7 ); - BAToUInt64( byteArray, 29 ); - BAToUInt64( byteArray, 13 ); - BAToUInt64( byteArray, 35 ); - BAToUInt64( byteArray, 44 ); - BAToUInt64( byteArray, 43 ); + BAToUInt64(byteArray, 3); + BAToUInt64(byteArray, 0); + BAToUInt64(byteArray, 21); + BAToUInt64(byteArray, 7); + BAToUInt64(byteArray, 29); + BAToUInt64(byteArray, 13); + BAToUInt64(byteArray, 35); + BAToUInt64(byteArray, 44); + BAToUInt64(byteArray, 43); } } diff --git a/snippets/csharp/System/Boolean/CompareTo/cat.cs b/snippets/csharp/System/Boolean/CompareTo/cat.cs index 970c1ff1677..343ff0ca9ba 100644 --- a/snippets/csharp/System/Boolean/CompareTo/cat.cs +++ b/snippets/csharp/System/Boolean/CompareTo/cat.cs @@ -10,95 +10,94 @@ class Sample { public static void Main() { - string nl = Environment.NewLine; - string msg = "{0}The following is the result of using the generic and non-generic{0}" + - "versions of the CompareTo method for several base types:{0}"; + string nl = Environment.NewLine; + string msg = "{0}The following is the result of using the generic and non-generic{0}" + + "versions of the CompareTo method for several base types:{0}"; - DateTime now = DateTime.Now; -// Time span = 11 days, 22 hours, 33 minutes, 44 seconds - TimeSpan tsX = new TimeSpan(11, 22, 33, 44); -// Version = 1.2.333.4 - Version versX = new Version("1.2.333.4"); -// Guid = CA761232-ED42-11CE-BACD-00AA0057B223 - Guid guidX = new Guid("{CA761232-ED42-11CE-BACD-00AA0057B223}"); + DateTime now = DateTime.Now; + // Time span = 11 days, 22 hours, 33 minutes, 44 seconds + TimeSpan tsX = new(11, 22, 33, 44); + // Version = 1.2.333.4 + Version versX = new("1.2.333.4"); + // Guid = CA761232-ED42-11CE-BACD-00AA0057B223 + Guid guidX = new("{CA761232-ED42-11CE-BACD-00AA0057B223}"); - Boolean a1 = true, a2 = true; - Byte b1 = 1, b2 = 1; - Int16 c1 = -2, c2 = 2; - Int32 d1 = 3, d2 = 3; - Int64 e1 = 4, e2 = -4; - Decimal f1 = -5.5m, f2 = 5.5m; - Single g1 = 6.6f, g2 = 6.6f; - Double h1 = 7.7d, h2 = -7.7d; - Char i1 = 'A', i2 = 'A'; - String j1 = "abc", j2 = "abc"; - DateTime k1 = now, k2 = now; - TimeSpan l1 = tsX, l2 = tsX; - Version m1 = versX, m2 = new Version("2.0"); - Guid n1 = guidX, n2 = guidX; + bool a1 = true, a2 = true; + byte b1 = 1, b2 = 1; + short c1 = -2, c2 = 2; + int d1 = 3, d2 = 3; + long e1 = 4, e2 = -4; + decimal f1 = -5.5m, f2 = 5.5m; + float g1 = 6.6f, g2 = 6.6f; + double h1 = 7.7d, h2 = -7.7d; + char i1 = 'A', i2 = 'A'; + string j1 = "abc", j2 = "abc"; + DateTime k1 = now, k2 = now; + TimeSpan l1 = tsX, l2 = tsX; + Version m1 = versX, m2 = new("2.0"); + Guid n1 = guidX, n2 = guidX; -// The following types are not CLS-compliant. - SByte w1 = 8, w2 = 8; - UInt16 x1 = 9, x2 = 9; - UInt32 y1 = 10, y2 = 10; - UInt64 z1 = 11, z2 = 11; -// - Console.WriteLine(msg, nl); - try + // The following types are not CLS-compliant. + sbyte w1 = 8, w2 = 8; + ushort x1 = 9, x2 = 9; + uint y1 = 10, y2 = 10; + ulong z1 = 11, z2 = 11; + // + Console.WriteLine(msg, nl); + try { -// The second and third Show method call parameters are automatically boxed because -// the second and third Show method declaration arguments expect type Object. + // The second and third Show method call parameters are automatically boxed because + // the second and third Show method declaration arguments expect type Object. - Show("Boolean: ", a1, a2, a1.CompareTo(a2), a1.CompareTo((Object)a2)); - Show("Byte: ", b1, b2, b1.CompareTo(b2), b1.CompareTo((Object)b2)); - Show("Int16: ", c1, c2, c1.CompareTo(c2), c1.CompareTo((Object)c2)); - Show("Int32: ", d1, d2, d1.CompareTo(d2), d1.CompareTo((Object)d2)); - Show("Int64: ", e1, e2, e1.CompareTo(e2), e1.CompareTo((Object)e2)); - Show("Decimal: ", f1, f2, f1.CompareTo(f2), f1.CompareTo((Object)f2)); - Show("Single: ", g1, g2, g1.CompareTo(g2), g1.CompareTo((Object)g2)); - Show("Double: ", h1, h2, h1.CompareTo(h2), h1.CompareTo((Object)h2)); - Show("Char: ", i1, i2, i1.CompareTo(i2), i1.CompareTo((Object)i2)); - Show("String: ", j1, j2, j1.CompareTo(j2), j1.CompareTo((Object)j2)); - Show("DateTime: ", k1, k2, k1.CompareTo(k2), k1.CompareTo((Object)k2)); - Show("TimeSpan: ", l1, l2, l1.CompareTo(l2), l1.CompareTo((Object)l2)); - Show("Version: ", m1, m2, m1.CompareTo(m2), m1.CompareTo((Object)m2)); - Show("Guid: ", n1, n2, n1.CompareTo(n2), n1.CompareTo((Object)n2)); -// - Console.WriteLine("{0}The following types are not CLS-compliant:", nl); - Show("SByte: ", w1, w2, w1.CompareTo(w2), w1.CompareTo((Object)w2)); - Show("UInt16: ", x1, x2, x1.CompareTo(x2), x1.CompareTo((Object)x2)); - Show("UInt32: ", y1, y2, y1.CompareTo(y2), y1.CompareTo((Object)y2)); - Show("UInt64: ", z1, z2, z1.CompareTo(z2), z1.CompareTo((Object)z2)); + Show("Boolean: ", a1, a2, a1.CompareTo(a2), a1.CompareTo((object)a2)); + Show("Byte: ", b1, b2, b1.CompareTo(b2), b1.CompareTo((object)b2)); + Show("Int16: ", c1, c2, c1.CompareTo(c2), c1.CompareTo((object)c2)); + Show("Int32: ", d1, d2, d1.CompareTo(d2), d1.CompareTo((object)d2)); + Show("Int64: ", e1, e2, e1.CompareTo(e2), e1.CompareTo((object)e2)); + Show("Decimal: ", f1, f2, f1.CompareTo(f2), f1.CompareTo((object)f2)); + Show("Single: ", g1, g2, g1.CompareTo(g2), g1.CompareTo((object)g2)); + Show("Double: ", h1, h2, h1.CompareTo(h2), h1.CompareTo((object)h2)); + Show("Char: ", i1, i2, i1.CompareTo(i2), i1.CompareTo((object)i2)); + Show("String: ", j1, j2, j1.CompareTo(j2), j1.CompareTo((object)j2)); + Show("DateTime: ", k1, k2, k1.CompareTo(k2), k1.CompareTo((object)k2)); + Show("TimeSpan: ", l1, l2, l1.CompareTo(l2), l1.CompareTo((object)l2)); + Show("Version: ", m1, m2, m1.CompareTo(m2), m1.CompareTo((object)m2)); + Show("Guid: ", n1, n2, n1.CompareTo(n2), n1.CompareTo((object)n2)); + // + Console.WriteLine($"{nl}The following types are not CLS-compliant:"); + Show("SByte: ", w1, w2, w1.CompareTo(w2), w1.CompareTo((object)w2)); + Show("UInt16: ", x1, x2, x1.CompareTo(x2), x1.CompareTo((object)x2)); + Show("UInt32: ", y1, y2, y1.CompareTo(y2), y1.CompareTo((object)y2)); + Show("UInt64: ", z1, z2, z1.CompareTo(z2), z1.CompareTo((object)z2)); } - catch (Exception e) + catch (Exception e) { - Console.WriteLine(e); + Console.WriteLine(e); } } - public static void Show(string caption, Object var1, Object var2, + public static void Show(string caption, object var1, object var2, int resultGeneric, int resultNonGeneric) { - string relation; + string relation; - Console.Write(caption); - if (resultGeneric == resultNonGeneric) + Console.Write(caption); + if (resultGeneric == resultNonGeneric) { - if (resultGeneric < 0) relation = "less than"; - else if (resultGeneric > 0) relation = "greater than"; - else relation = "equal to"; - Console.WriteLine("{0} is {1} {2}", var1, relation, var2); + if (resultGeneric < 0) relation = "less than"; + else if (resultGeneric > 0) relation = "greater than"; + else relation = "equal to"; + Console.WriteLine($"{var1} is {relation} {var2}"); } -// The following condition will never occur because the generic and non-generic -// CompareTo methods are equivalent. + // The following condition will never occur because the generic and non-generic + // CompareTo methods are equivalent. - else + else { - Console.WriteLine("Generic CompareTo = {0}; non-generic CompareTo = {1}", - resultGeneric, resultNonGeneric); + Console.WriteLine($"Generic CompareTo = {resultGeneric}; non-generic CompareTo = {resultNonGeneric}"); } - } + } } /* This example produces the following results: diff --git a/snippets/csharp/System/Boolean/Overview/binary1.cs b/snippets/csharp/System/Boolean/Overview/binary1.cs index 157211ddb53..79059d054bf 100644 --- a/snippets/csharp/System/Boolean/Overview/binary1.cs +++ b/snippets/csharp/System/Boolean/Overview/binary1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example1 @@ -6,19 +6,19 @@ public class Example1 public static void Main() { bool[] flags = { true, false }; - foreach (var flag in flags) + foreach (bool flag in flags) { // Get binary representation of flag. - Byte value = BitConverter.GetBytes(flag)[0]; + byte value = BitConverter.GetBytes(flag)[0]; Console.WriteLine($"Original value: {flag}"); Console.WriteLine($"Binary value: {value} ({GetBinaryString(value)})"); // Restore the flag from its binary representation. - bool newFlag = BitConverter.ToBoolean(new Byte[] { value }, 0); + bool newFlag = BitConverter.ToBoolean(new byte[] { value }, 0); Console.WriteLine($"Restored value: {newFlag}{Environment.NewLine}"); } } - private static string GetBinaryString(Byte value) + private static string GetBinaryString(byte value) { string retVal = Convert.ToString(value, 2); return new string('0', 8 - retVal.Length) + retVal; diff --git a/snippets/csharp/System/Boolean/Overview/conversion1.cs b/snippets/csharp/System/Boolean/Overview/conversion1.cs index a73bec266ee..18ec60328cb 100644 --- a/snippets/csharp/System/Boolean/Overview/conversion1.cs +++ b/snippets/csharp/System/Boolean/Overview/conversion1.cs @@ -3,23 +3,23 @@ public class Example2 { - public static void Main() - { - Byte byteValue = 12; - Console.WriteLine(Convert.ToBoolean(byteValue)); - Byte byteValue2 = 0; - Console.WriteLine(Convert.ToBoolean(byteValue2)); - int intValue = -16345; - Console.WriteLine(Convert.ToBoolean(intValue)); - long longValue = 945; - Console.WriteLine(Convert.ToBoolean(longValue)); - SByte sbyteValue = -12; - Console.WriteLine(Convert.ToBoolean(sbyteValue)); - double dblValue = 0; - Console.WriteLine(Convert.ToBoolean(dblValue)); - float sngValue = .0001f; - Console.WriteLine(Convert.ToBoolean(sngValue)); - } + public static void Main() + { + byte byteValue = 12; + Console.WriteLine(Convert.ToBoolean(byteValue)); + byte byteValue2 = 0; + Console.WriteLine(Convert.ToBoolean(byteValue2)); + int intValue = -16345; + Console.WriteLine(Convert.ToBoolean(intValue)); + long longValue = 945; + Console.WriteLine(Convert.ToBoolean(longValue)); + sbyte sbyteValue = -12; + Console.WriteLine(Convert.ToBoolean(sbyteValue)); + double dblValue = 0; + Console.WriteLine(Convert.ToBoolean(dblValue)); + float sngValue = .0001f; + Console.WriteLine(Convert.ToBoolean(sngValue)); + } } // The example displays the following output: // True diff --git a/snippets/csharp/System/Boolean/Overview/conversion3.cs b/snippets/csharp/System/Boolean/Overview/conversion3.cs index 5cc0408da7f..d8d6076b3e5 100644 --- a/snippets/csharp/System/Boolean/Overview/conversion3.cs +++ b/snippets/csharp/System/Boolean/Overview/conversion3.cs @@ -1,28 +1,28 @@ -// +// using System; public class Example3 { - public static void Main() - { - bool flag = true; + public static void Main() + { + bool flag = true; - byte byteValue; - byteValue = Convert.ToByte(flag); - Console.WriteLine($"{flag} -> {byteValue}"); + byte byteValue; + byteValue = Convert.ToByte(flag); + Console.WriteLine($"{flag} -> {byteValue}"); - sbyte sbyteValue; - sbyteValue = Convert.ToSByte(flag); - Console.WriteLine($"{flag} -> {sbyteValue}"); + sbyte sbyteValue; + sbyteValue = Convert.ToSByte(flag); + Console.WriteLine($"{flag} -> {sbyteValue}"); - double dblValue; - dblValue = Convert.ToDouble(flag); - Console.WriteLine($"{flag} -> {dblValue}"); + double dblValue; + dblValue = Convert.ToDouble(flag); + Console.WriteLine($"{flag} -> {dblValue}"); - int intValue; - intValue = Convert.ToInt32(flag); - Console.WriteLine($"{flag} -> {intValue}"); - } + int intValue; + intValue = Convert.ToInt32(flag); + Console.WriteLine($"{flag} -> {intValue}"); + } } // The example displays the following output: // True -> 1 diff --git a/snippets/csharp/System/Boolean/Overview/format3.cs b/snippets/csharp/System/Boolean/Overview/format3.cs index f9d31889233..22c3fb96351 100644 --- a/snippets/csharp/System/Boolean/Overview/format3.cs +++ b/snippets/csharp/System/Boolean/Overview/format3.cs @@ -4,57 +4,55 @@ public class Example4 { - public static void Main() - { - String[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" }; - foreach (var cultureName in cultureNames) { - bool value = true; - CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName); - BooleanFormatter formatter = new BooleanFormatter(culture); - - string result = string.Format(formatter, "Value for '{0}': {1}", culture.Name, value); - Console.WriteLine(result); - } - } + public static void Main() + { + string[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" }; + foreach (string cultureName in cultureNames) + { + bool value = true; + CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName); + BooleanFormatter formatter = new(culture); + + string result = string.Format(formatter, "Value for '{0}': {1}", culture.Name, value); + Console.WriteLine(result); + } + } } public class BooleanFormatter : ICustomFormatter, IFormatProvider { - private CultureInfo culture; - - public BooleanFormatter() : this(CultureInfo.CurrentCulture) - { } - - public BooleanFormatter(CultureInfo culture) - { - this.culture = culture; - } - - public Object GetFormat(Type formatType) - { - if (formatType == typeof(ICustomFormatter)) - return this; - else - return null; - } - - public string Format(string fmt, Object arg, IFormatProvider formatProvider) - { - // Exit if another format provider is used. - if (! formatProvider.Equals(this)) return null; - - // Exit if the type to be formatted is not a Boolean - if (! (arg is Boolean)) return null; - - bool value = (bool) arg; - return culture.Name switch - { - "en-US" => value.ToString(), - "fr-FR" => value ? "vrai" : "faux", - "ru-RU" => value ? "верно" : "неверно", - _ => value.ToString(), - }; - } + private CultureInfo culture; + + public BooleanFormatter() : this(CultureInfo.CurrentCulture) + { } + + public BooleanFormatter(CultureInfo culture) => this.culture = culture; + + public object GetFormat(Type formatType) + { + if (formatType == typeof(ICustomFormatter)) + return this; + else + return null; + } + + public string Format(string fmt, object arg, IFormatProvider formatProvider) + { + // Exit if another format provider is used. + if (!formatProvider.Equals(this)) return null; + + // Exit if the type to be formatted is not a Boolean + if (!(arg is bool)) return null; + + bool value = (bool)arg; + return culture.Name switch + { + "en-US" => value.ToString(), + "fr-FR" => value ? "vrai" : "faux", + "ru-RU" => value ? "верно" : "неверно", + _ => value.ToString(), + }; + } } // The example displays the following output: // Value for '': True diff --git a/snippets/csharp/System/Boolean/Overview/operations1.cs b/snippets/csharp/System/Boolean/Overview/operations1.cs index bd47be79043..d6c61bbd2d8 100644 --- a/snippets/csharp/System/Boolean/Overview/operations1.cs +++ b/snippets/csharp/System/Boolean/Overview/operations1.cs @@ -5,87 +5,94 @@ public class Example5 { - public static void Main() - { - // Initialize flag variables. - bool isRedirected = false; - bool isBoth = false; - String fileName = ""; - StreamWriter sw = null; + public static void Main() + { + // Initialize flag variables. + bool isRedirected = false; + bool isBoth = false; + string fileName = ""; + StreamWriter sw = null; - // Get any command line arguments. - String[] args = Environment.GetCommandLineArgs(); - // Handle any arguments. - if (args.Length > 1) { - for (int ctr = 1; ctr < args.Length; ctr++) { - String arg = args[ctr]; - if (arg.StartsWith("/") || arg.StartsWith("-")) { - switch (arg.Substring(1).ToLower()) - { - case "f": - isRedirected = true; - if (args.Length < ctr + 2) { - ShowSyntax("The /f switch must be followed by a filename."); - return; - } - fileName = args[ctr + 1]; - ctr++; - break; - case "b": - isBoth = true; - break; - default: - ShowSyntax(String.Format("The {0} switch is not supported", - args[ctr])); - return; - } + // Get any command line arguments. + string[] args = Environment.GetCommandLineArgs(); + // Handle any arguments. + if (args.Length > 1) + { + for (int ctr = 1; ctr < args.Length; ctr++) + { + string arg = args[ctr]; + if (arg.StartsWith("/") || arg.StartsWith("-")) + { + switch (arg.Substring(1).ToLower()) + { + case "f": + isRedirected = true; + if (args.Length < ctr + 2) + { + ShowSyntax("The /f switch must be followed by a filename."); + return; + } + fileName = args[ctr + 1]; + ctr++; + break; + case "b": + isBoth = true; + break; + default: + ShowSyntax($"The {args[ctr]} switch is not supported"); + return; + } + } } - } - } + } - // If isBoth is True, isRedirected must be True. - if (isBoth && ! isRedirected) { - ShowSyntax("The /f switch must be used if /b is used."); - return; - } + // If isBoth is True, isRedirected must be True. + if (isBoth && !isRedirected) + { + ShowSyntax("The /f switch must be used if /b is used."); + return; + } - // Handle output. - if (isRedirected) { - sw = new StreamWriter(fileName); - if (!isBoth) Console.SetOut(sw); - } - String msg = String.Format("Application began at {0}", DateTime.Now); - Console.WriteLine(msg); - if (isBoth) sw.WriteLine(msg); - Thread.Sleep(5000); - msg = String.Format("Application ended normally at {0}", DateTime.Now); - Console.WriteLine(msg); - if (isBoth) sw.WriteLine(msg); - if (isRedirected) sw.Close(); - } + // Handle output. + if (isRedirected) + { + sw = new(fileName); + if (!isBoth) Console.SetOut(sw); + } + string msg = $"Application began at {DateTime.Now}"; + Console.WriteLine(msg); + if (isBoth) sw.WriteLine(msg); + Thread.Sleep(5000); + msg = $"Application ended normally at {DateTime.Now}"; + Console.WriteLine(msg); + if (isBoth) sw.WriteLine(msg); + if (isRedirected) sw.Close(); + } - private static void ShowSyntax(String errMsg) - { - Console.WriteLine(errMsg); - Console.WriteLine("\nSyntax: Example [[/f [/b]]\n"); - } + private static void ShowSyntax(string errMsg) + { + Console.WriteLine(errMsg); + Console.WriteLine("\nSyntax: Example [[/f [/b]]\n"); + } } // public class Evaluation { - public void SomeMethod() - { - bool booleanValue = false; + public void SomeMethod() + { + bool booleanValue = false; - // - if (booleanValue == true) { - // - } + // + if (booleanValue == true) + { + // + } - // - if (booleanValue) { - // - } - } + // + if (booleanValue) + { + // + } + } } diff --git a/snippets/csharp/System/Boolean/Overview/operations2.cs b/snippets/csharp/System/Boolean/Overview/operations2.cs index d64b1de0602..c432131976d 100644 --- a/snippets/csharp/System/Boolean/Overview/operations2.cs +++ b/snippets/csharp/System/Boolean/Overview/operations2.cs @@ -1,21 +1,22 @@ -// +// using System; public class Example6 { - public static void Main() - { - bool[] hasServiceCharges = { true, false }; - Decimal subtotal = 120.62m; - Decimal shippingCharge = 2.50m; - Decimal serviceCharge = 5.00m; + public static void Main() + { + bool[] hasServiceCharges = { true, false }; + decimal subtotal = 120.62m; + decimal shippingCharge = 2.50m; + decimal serviceCharge = 5.00m; - foreach (var hasServiceCharge in hasServiceCharges) { - Decimal total = subtotal + shippingCharge + - (hasServiceCharge ? serviceCharge : 0); - Console.WriteLine($"hasServiceCharge = {hasServiceCharge}: The total is {total:C2}."); - } - } + foreach (bool hasServiceCharge in hasServiceCharges) + { + decimal total = subtotal + shippingCharge + + (hasServiceCharge ? serviceCharge : 0); + Console.WriteLine($"hasServiceCharge = {hasServiceCharge}: The total is {total:C2}."); + } + } } // The example displays output like the following: // hasServiceCharge = True: The total is $128.12. diff --git a/snippets/csharp/System/Boolean/Overview/parse2.cs b/snippets/csharp/System/Boolean/Overview/parse2.cs index 9ab8deea0c0..8e3e74a2d9a 100644 --- a/snippets/csharp/System/Boolean/Overview/parse2.cs +++ b/snippets/csharp/System/Boolean/Overview/parse2.cs @@ -1,37 +1,42 @@ -// +// using System; public class Example7 { - public static void Main() - { - string[] values = [ null, String.Empty, "True", "False", + public static void Main() + { + string[] values = [ null, string.Empty, "True", "False", "true", "false", " true ", "TrUe", "fAlSe", "fa lse", "0", "1", "-1", "string" ]; - // Parse strings using the Boolean.Parse method. - foreach (var value in values) { - try { - bool flag = Boolean.Parse(value); - Console.WriteLine($"'{value}' --> {flag}"); - } - catch (ArgumentException) { - Console.WriteLine("Cannot parse a null string."); - } - catch (FormatException) { - Console.WriteLine($"Cannot parse '{value}'."); - } - } - Console.WriteLine(); - // Parse strings using the Boolean.TryParse method. - foreach (var value in values) { - bool flag = false; - if (Boolean.TryParse(value, out flag)) - Console.WriteLine($"'{value}' --> {flag}"); - else - Console.WriteLine($"Unable to parse '{value}'"); - } - } + // Parse strings using the Boolean.Parse method. + foreach (string value in values) + { + try + { + bool flag = bool.Parse(value); + Console.WriteLine($"'{value}' --> {flag}"); + } + catch (ArgumentException) + { + Console.WriteLine("Cannot parse a null string."); + } + catch (FormatException) + { + Console.WriteLine($"Cannot parse '{value}'."); + } + } + Console.WriteLine(); + // Parse strings using the Boolean.TryParse method. + foreach (string value in values) + { + bool flag = false; + if (bool.TryParse(value, out flag)) + Console.WriteLine($"'{value}' --> {flag}"); + else + Console.WriteLine($"Unable to parse '{value}'"); + } + } } // The example displays the following output: // Cannot parse a null string. diff --git a/snippets/csharp/System/Boolean/Overview/parse3.cs b/snippets/csharp/System/Boolean/Overview/parse3.cs index 48d7a9f08fd..2aefe07c2ad 100644 --- a/snippets/csharp/System/Boolean/Overview/parse3.cs +++ b/snippets/csharp/System/Boolean/Overview/parse3.cs @@ -1,25 +1,28 @@ -// +// using System; public class Example8 { - public static void Main() - { - String[] values = [ "09", "12.6", "0", "-13 " ]; - foreach (var value in values) { - bool success, result; - int number; - success = Int32.TryParse(value, out number); - if (success) { - // The method throws no exceptions. - result = Convert.ToBoolean(number); - Console.WriteLine($"Converted '{value}' to {result}"); - } - else { - Console.WriteLine($"Unable to convert '{value}'"); - } - } - } + public static void Main() + { + string[] values = ["09", "12.6", "0", "-13 "]; + foreach (string value in values) + { + bool success, result; + int number; + success = int.TryParse(value, out number); + if (success) + { + // The method throws no exceptions. + result = Convert.ToBoolean(number); + Console.WriteLine($"Converted '{value}' to {result}"); + } + else + { + Console.WriteLine($"Unable to convert '{value}'"); + } + } + } } // The example displays the following output: // Converted '09' to True diff --git a/snippets/csharp/System/Boolean/Overview/size1.cs b/snippets/csharp/System/Boolean/Overview/size1.cs index 2e145259d26..6e22ec83b75 100644 --- a/snippets/csharp/System/Boolean/Overview/size1.cs +++ b/snippets/csharp/System/Boolean/Overview/size1.cs @@ -1,31 +1,32 @@ -// +// using System; public struct BoolStruct { - public bool flag1; - public bool flag2; - public bool flag3; - public bool flag4; - public bool flag5; + public bool flag1; + public bool flag2; + public bool flag3; + public bool flag4; + public bool flag5; } public class Example9 { - public static void Main() - { - unsafe { - BoolStruct b = new BoolStruct(); - bool* addr = (bool*) &b; - Console.WriteLine($"Size of BoolStruct: {sizeof(BoolStruct)}"); - Console.WriteLine("Field offsets:"); - Console.WriteLine($" flag1: {(bool*) &b.flag1 - addr}"); - Console.WriteLine($" flag2: {(bool*) &b.flag2 - addr}"); - Console.WriteLine($" flag3: {(bool*) &b.flag3 - addr}"); - Console.WriteLine($" flag4: {(bool*) &b.flag4 - addr}"); - Console.WriteLine($" flag5: {(bool*) &b.flag5 - addr}"); - } - } + public static void Main() + { + unsafe + { + BoolStruct b = new(); + bool* addr = (bool*)&b; + Console.WriteLine($"Size of BoolStruct: {sizeof(BoolStruct)}"); + Console.WriteLine("Field offsets:"); + Console.WriteLine($" flag1: {(bool*)&b.flag1 - addr}"); + Console.WriteLine($" flag2: {(bool*)&b.flag2 - addr}"); + Console.WriteLine($" flag3: {(bool*)&b.flag3 - addr}"); + Console.WriteLine($" flag4: {(bool*)&b.flag4 - addr}"); + Console.WriteLine($" flag5: {(bool*)&b.flag5 - addr}"); + } + } } // The example displays the following output: // Size of BoolStruct: 5 diff --git a/snippets/csharp/System/Boolean/Overview/tostring1.cs b/snippets/csharp/System/Boolean/Overview/tostring1.cs index 09cfd324cd8..49cea5c0712 100644 --- a/snippets/csharp/System/Boolean/Overview/tostring1.cs +++ b/snippets/csharp/System/Boolean/Overview/tostring1.cs @@ -1,16 +1,16 @@ -// +// using System; public class Example10 { - public static void Main() - { - bool raining = false; - bool busLate = true; + public static void Main() + { + bool raining = false; + bool busLate = true; - Console.WriteLine($"It is raining: {raining}"); - Console.WriteLine($"The bus is late: {busLate}"); - } + Console.WriteLine($"It is raining: {raining}"); + Console.WriteLine($"The bus is late: {busLate}"); + } } // The example displays the following output: // It is raining: False diff --git a/snippets/csharp/System/Boolean/Parse/booleanmembers.cs b/snippets/csharp/System/Boolean/Parse/booleanmembers.cs index 5ea8db2eca7..08dc1eddebf 100644 --- a/snippets/csharp/System/Boolean/Parse/booleanmembers.cs +++ b/snippets/csharp/System/Boolean/Parse/booleanmembers.cs @@ -1,14 +1,16 @@ using System; -public class BooleanMembers { +public class BooleanMembers +{ - public static void Main() { + public static void Main() + { // bool raining = false; bool busLate = true; - Console.WriteLine("raining.ToString() returns {0}", raining); - Console.WriteLine("busLate.ToString() returns {0}", busLate); + Console.WriteLine($"raining.ToString() returns {raining}"); + Console.WriteLine($"busLate.ToString() returns {busLate}"); // The example displays the following output: // raining.ToString() returns False // busLate.ToString() returns True @@ -20,7 +22,7 @@ public static void Main() { input = bool.TrueString; val = bool.Parse(input); - Console.WriteLine("'{0}' parsed as {1}", input, val); + Console.WriteLine($"'{input}' parsed as {val}"); // The example displays the following output: // 'True' parsed as True // diff --git a/snippets/csharp/System/Boolean/TryParse/tryparseex.cs b/snippets/csharp/System/Boolean/TryParse/tryparseex.cs index 3372ac53f1e..39fdba3c409 100644 --- a/snippets/csharp/System/Boolean/TryParse/tryparseex.cs +++ b/snippets/csharp/System/Boolean/TryParse/tryparseex.cs @@ -3,20 +3,20 @@ public class Example { - public static void Main() - { - string[] values = { null, String.Empty, "True", "False", + public static void Main() + { + string[] values = { null, string.Empty, "True", "False", "true", "false", " true ", "0", "1", "-1", "string" }; - foreach (var value in values) { - bool flag; - if (Boolean.TryParse(value, out flag)) - Console.WriteLine("'{0}' --> {1}", value, flag); - else - Console.WriteLine("Unable to parse '{0}'.", - value == null ? "" : value); - } - } + foreach (string value in values) + { + bool flag; + if (bool.TryParse(value, out flag)) + Console.WriteLine($"'{value}' --> {flag}"); + else + Console.WriteLine($"Unable to parse '{(value == null ? "" : value)}'."); + } + } } // The example displays the following output: // Unable to parse ''. diff --git a/snippets/csharp/System/Buffer/ByteLength/bytelength.cs b/snippets/csharp/System/Buffer/ByteLength/bytelength.cs index 067edd06a80..31cab5e9c23 100644 --- a/snippets/csharp/System/Buffer/ByteLength/bytelength.cs +++ b/snippets/csharp/System/Buffer/ByteLength/bytelength.cs @@ -6,41 +6,41 @@ class ByteLengthDemo { const string formatter = "{0,10}{1,20}{2,9}{3,12}"; - public static void ArrayInfo( Array arr, string name ) + public static void ArrayInfo(Array arr, string name) { - int byteLength = Buffer.ByteLength( arr ); + int byteLength = Buffer.ByteLength(arr); // Display the array name, type, Length, and ByteLength. - Console.WriteLine( formatter, name, arr.GetType( ), - arr.Length, byteLength ); + Console.WriteLine(formatter, name, arr.GetType(), + arr.Length, byteLength); } - public static void Main( ) + public static void Main() { - byte[ ] bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; - bool[ ] bools = { true, false, true, false, true }; - char[ ] chars = { ' ', '$', '\"', 'A', '{' }; - short[ ] shorts = { 258, 259, 260, 261, 262, 263 }; - float[ ] singles = { 1, 678, 2.37E33F, .00415F, 8.9F }; - double[ ] doubles = { 2E-22, .003, 4.4E44, 555E55 }; - long[ ] longs = { 1, 10, 100, 1000, 10000, 100000 }; + byte[] bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; + bool[] bools = { true, false, true, false, true }; + char[] chars = { ' ', '$', '\"', 'A', '{' }; + short[] shorts = { 258, 259, 260, 261, 262, 263 }; + float[] singles = { 1, 678, 2.37E33F, .00415F, 8.9F }; + double[] doubles = { 2E-22, .003, 4.4E44, 555E55 }; + long[] longs = { 1, 10, 100, 1000, 10000, 100000 }; Console.WriteLine( "This example of the Buffer.ByteLength( Array ) " + - "\nmethod generates the following output.\n" ); - Console.WriteLine( formatter, "Array name", "Array type", - "Length", "ByteLength" ); - Console.WriteLine( formatter, "----------", "----------", - "------", "----------" ); + "\nmethod generates the following output.\n"); + Console.WriteLine(formatter, "Array name", "Array type", + "Length", "ByteLength"); + Console.WriteLine(formatter, "----------", "----------", + "------", "----------"); // Display the Length and ByteLength for each array. - ArrayInfo( bytes, "bytes" ); - ArrayInfo( bools, "bools" ); - ArrayInfo( chars, "chars" ); - ArrayInfo( shorts, "shorts" ); - ArrayInfo( singles, "singles" ); - ArrayInfo( doubles, "doubles" ); - ArrayInfo( longs, "longs" ); + ArrayInfo(bytes, "bytes"); + ArrayInfo(bools, "bools"); + ArrayInfo(chars, "chars"); + ArrayInfo(shorts, "shorts"); + ArrayInfo(singles, "singles"); + ArrayInfo(doubles, "doubles"); + ArrayInfo(longs, "longs"); } } diff --git a/snippets/csharp/System/Buffer/ByteLength/getbyte.cs b/snippets/csharp/System/Buffer/ByteLength/getbyte.cs index dd041e5eea1..e59798a254b 100644 --- a/snippets/csharp/System/Buffer/ByteLength/getbyte.cs +++ b/snippets/csharp/System/Buffer/ByteLength/getbyte.cs @@ -7,61 +7,61 @@ class GetByteDemo const string formatter = "{0,10}{1,10}{2,9} {3}"; // Display the array contents in hexadecimal. - public static void DisplayArray( Array arr, string name ) + public static void DisplayArray(Array arr, string name) { // Get the array element width; format the formatting string. - int elemWidth = Buffer.ByteLength( arr ) / arr.Length; - string format = String.Format( " {{0:X{0}}}", 2 * elemWidth ); + int elemWidth = Buffer.ByteLength(arr) / arr.Length; + string format = $" {{0:X{2 * elemWidth}}}"; // Display the array elements from right to left. - Console.Write( "{0,5}:", name ); - for( int loopX = arr.Length - 1; loopX >= 0; loopX-- ) - Console.Write( format, arr.GetValue( loopX ) ); - Console.WriteLine( ); + Console.Write($"{name,5}:"); + for (int loopX = arr.Length - 1; loopX >= 0; loopX--) + Console.Write(format, arr.GetValue(loopX)); + Console.WriteLine(); } - public static void ArrayInfo( Array arr, string name, int index ) + public static void ArrayInfo(Array arr, string name, int index) { - byte value = Buffer.GetByte( arr, index ); + byte value = Buffer.GetByte(arr, index); // Display the array name, index, and byte to be viewed. - Console.WriteLine( formatter, name, index, value, - String.Format( "0x{0:X2}", value ) ); + Console.WriteLine(formatter, name, index, value, + $"0x{value:X2}"); } - public static void Main( ) + public static void Main() { // These are the arrays to be viewed with GetByte. - long[ ] longs = + long[] longs = { 333333333333333333, 666666666666666666, 999999999999999999 }; - int[ ] ints = + int[] ints = { 111111111, 222222222, 333333333, 444444444, 555555555 }; - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "Buffer.GetByte( Array, int ) \n" + "method generates the following output.\n" + - "Note: The arrays are displayed from right to left.\n" ); - Console.WriteLine( " Values of arrays:\n" ); + "Note: The arrays are displayed from right to left.\n"); + Console.WriteLine(" Values of arrays:\n"); // Display the values of the arrays. - DisplayArray( longs, "longs" ); - DisplayArray( ints, "ints" ); - Console.WriteLine( ); + DisplayArray(longs, "longs"); + DisplayArray(ints, "ints"); + Console.WriteLine(); - Console.WriteLine( formatter, "Array", "index", "value", "" ); - Console.WriteLine( formatter, "-----", "-----", "-----", - "----" ); + Console.WriteLine(formatter, "Array", "index", "value", ""); + Console.WriteLine(formatter, "-----", "-----", "-----", + "----"); // Display the Length and ByteLength for each array. - ArrayInfo( ints, "ints", 0 ); - ArrayInfo( ints, "ints", 7 ); - ArrayInfo( ints, "ints", 10 ); - ArrayInfo( ints, "ints", 17 ); - ArrayInfo( longs, "longs", 0 ); - ArrayInfo( longs, "longs", 6 ); - ArrayInfo( longs, "longs", 10 ); - ArrayInfo( longs, "longs", 17 ); - ArrayInfo( longs, "longs", 21 ); + ArrayInfo(ints, "ints", 0); + ArrayInfo(ints, "ints", 7); + ArrayInfo(ints, "ints", 10); + ArrayInfo(ints, "ints", 17); + ArrayInfo(longs, "longs", 0); + ArrayInfo(longs, "longs", 6); + ArrayInfo(longs, "longs", 10); + ArrayInfo(longs, "longs", 17); + ArrayInfo(longs, "longs", 21); } } diff --git a/snippets/csharp/System/Buffer/ByteLength/setbyte.cs b/snippets/csharp/System/Buffer/ByteLength/setbyte.cs index d61394cdef7..e13dce3192f 100644 --- a/snippets/csharp/System/Buffer/ByteLength/setbyte.cs +++ b/snippets/csharp/System/Buffer/ByteLength/setbyte.cs @@ -5,53 +5,53 @@ class SetByteDemo { // Display the array contents in hexadecimal. - public static void DisplayArray( Array arr, string name ) + public static void DisplayArray(Array arr, string name) { // Get the array element width; format the formatting string. - int elemWidth = Buffer.ByteLength( arr ) / arr.Length; - string format = String.Format( " {{0:X{0}}}", 2 * elemWidth ); + int elemWidth = Buffer.ByteLength(arr) / arr.Length; + string format = $" {{0:X{2 * elemWidth}}}"; // Display the array elements from right to left. - Console.Write( "{0,7}:", name ); - for( int loopX = arr.Length - 1; loopX >= 0; loopX-- ) - Console.Write( format, arr.GetValue( loopX ) ); - Console.WriteLine( ); + Console.Write($"{name,7}:"); + for (int loopX = arr.Length - 1; loopX >= 0; loopX--) + Console.Write(format, arr.GetValue(loopX)); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { // These are the arrays to be modified with SetByte. - short[ ] shorts = new short[ 10 ]; - long[ ] longs = new long[ 3 ]; + short[] shorts = new short[10]; + long[] longs = new long[3]; - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "Buffer.SetByte( Array, int, byte ) \n" + "method generates the following output.\n" + - "Note: The arrays are displayed from right to left.\n" ); - Console.WriteLine( " Initial values of arrays:\n" ); + "Note: The arrays are displayed from right to left.\n"); + Console.WriteLine(" Initial values of arrays:\n"); // Display the initial values of the arrays. - DisplayArray( shorts, "shorts" ); - DisplayArray( longs, "longs" ); + DisplayArray(shorts, "shorts"); + DisplayArray(longs, "longs"); // Copy two regions of source array to destination array, // and two overlapped copies from source to source. - Console.WriteLine( "\n" + + Console.WriteLine("\n" + " Array values after setting byte 3 = 25, \n" + - " byte 6 = 64, byte 12 = 121, and byte 17 = 196:\n" ); + " byte 6 = 64, byte 12 = 121, and byte 17 = 196:\n"); - Buffer.SetByte( shorts, 3, 25 ); - Buffer.SetByte( shorts, 6, 64 ); - Buffer.SetByte( shorts, 12, 121 ); - Buffer.SetByte( shorts, 17, 196 ); - Buffer.SetByte( longs, 3, 25 ); - Buffer.SetByte( longs, 6, 64 ); - Buffer.SetByte( longs, 12, 121 ); - Buffer.SetByte( longs, 17, 196 ); + Buffer.SetByte(shorts, 3, 25); + Buffer.SetByte(shorts, 6, 64); + Buffer.SetByte(shorts, 12, 121); + Buffer.SetByte(shorts, 17, 196); + Buffer.SetByte(longs, 3, 25); + Buffer.SetByte(longs, 6, 64); + Buffer.SetByte(longs, 12, 121); + Buffer.SetByte(longs, 17, 196); // Display the arrays again. - DisplayArray( shorts, "shorts" ); - DisplayArray( longs, "longs" ); + DisplayArray(shorts, "shorts"); + DisplayArray(longs, "longs"); } } diff --git a/snippets/csharp/System/Buffer/Overview/bcopy.cs b/snippets/csharp/System/Buffer/Overview/bcopy.cs index fb90b33e633..d31c4636837 100644 --- a/snippets/csharp/System/Buffer/Overview/bcopy.cs +++ b/snippets/csharp/System/Buffer/Overview/bcopy.cs @@ -7,17 +7,17 @@ class Example public static void DisplayArray(Array arr, string name) { Console.WindowWidth = 120; - Console.Write("{0,11}:", name); + Console.Write($"{name,11}:"); for (int ctr = 0; ctr < arr.Length; ctr++) { byte[] bytes; if (arr is long[]) - bytes = BitConverter.GetBytes((long) arr.GetValue(ctr)); + bytes = BitConverter.GetBytes((long)arr.GetValue(ctr)); else - bytes = BitConverter.GetBytes((short) arr.GetValue(ctr)); + bytes = BitConverter.GetBytes((short)arr.GetValue(ctr)); foreach (byte byteValue in bytes) - Console.Write(" {0:X2}", byteValue); + Console.Write($" {byteValue:X2}"); } Console.WriteLine(); } @@ -27,25 +27,25 @@ public static void DisplayArrayValues(Array arr, string name) { // Get the length of one element in the array. int elementLength = Buffer.ByteLength(arr) / arr.Length; - string formatString = String.Format(" {{0:X{0}}}", 2 * elementLength); - Console.Write( "{0,11}:", name); + string formatString = $" {{0:X{2 * elementLength}}}"; + Console.Write($"{name,11}:"); for (int ctr = 0; ctr < arr.Length; ctr++) Console.Write(formatString, arr.GetValue(ctr)); Console.WriteLine(); } - public static void Main( ) + public static void Main() { // These are the source and destination arrays for BlockCopy. - short[] src = { 258, 259, 260, 261, 262, 263, 264, + short[] src = { 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270 }; long[] dest = { 17, 18, 19, 20 }; // Display the initial value of the arrays in memory. - Console.WriteLine( "Initial values of arrays:"); + Console.WriteLine("Initial values of arrays:"); Console.WriteLine(" Array values as Bytes:"); - DisplayArray(src, "src" ); + DisplayArray(src, "src"); DisplayArray(dest, "dest"); Console.WriteLine(" Array values:"); DisplayArrayValues(src, "src"); @@ -75,7 +75,7 @@ public static void Main( ) Console.WriteLine(); // Copy overlapping range of bytes 4-10 to index 5 in source. - Buffer.BlockCopy(src, 4, src, 5, 7 ); + Buffer.BlockCopy(src, 4, src, 5, 7); Console.WriteLine("Buffer.BlockCopy( src, 4, src, 5, 7)"); Console.WriteLine(" Array values as Bytes:"); DisplayArray(src, "src"); diff --git a/snippets/csharp/System/Buffer/Overview/buffer.cs b/snippets/csharp/System/Buffer/Overview/buffer.cs index e7ffc61ec50..7328a666ee9 100644 --- a/snippets/csharp/System/Buffer/Overview/buffer.cs +++ b/snippets/csharp/System/Buffer/Overview/buffer.cs @@ -5,43 +5,41 @@ class BufferClassDemo { // Display the array elements from right to left in hexadecimal. - public static void DisplayArray( short[ ] arr ) + public static void DisplayArray(short[] arr) { - Console.Write( " arr:" ); - for( int loopX = arr.Length - 1; loopX >= 0; loopX-- ) - Console.Write( " {0:X4}", arr[ loopX ] ); - Console.WriteLine( ); + Console.Write(" arr:"); + for (int loopX = arr.Length - 1; loopX >= 0; loopX--) + Console.Write($" {arr[loopX]:X4}"); + Console.WriteLine(); } - public static void Main( ) + public static void Main() { // This array is to be modified and displayed. - short[ ] arr = { 258, 259, 260, 261, 262, 263, 264, + short[] arr = { 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271 }; - Console.WriteLine( "This example of the Buffer class " + + Console.WriteLine("This example of the Buffer class " + "methods generates the following output.\n" + - "Note: The array is displayed from right to left.\n" ); - Console.WriteLine( "Initial values of array:\n" ); + "Note: The array is displayed from right to left.\n"); + Console.WriteLine("Initial values of array:\n"); // Display the initial array values and ByteLength. - DisplayArray( arr ); - Console.WriteLine( "\nBuffer.ByteLength( arr ): {0}", - Buffer.ByteLength( arr ) ); + DisplayArray(arr); + Console.WriteLine($"\nBuffer.ByteLength( arr ): {Buffer.ByteLength(arr)}"); // Copy a region of the array; set a byte within the array. - Console.WriteLine( "\nCall these methods: \n" + + Console.WriteLine("\nCall these methods: \n" + " Buffer.BlockCopy( arr, 5, arr, 16, 9 ),\n" + - " Buffer.SetByte( arr, 7, 170 ).\n" ); + " Buffer.SetByte( arr, 7, 170 ).\n"); - Buffer.BlockCopy( arr, 5, arr, 16, 9 ); - Buffer.SetByte( arr, 7, 170 ); + Buffer.BlockCopy(arr, 5, arr, 16, 9); + Buffer.SetByte(arr, 7, 170); // Display the array and a byte within the array. - Console.WriteLine( "Final values of array:\n" ); - DisplayArray( arr ); - Console.WriteLine( "\nBuffer.GetByte( arr, 26 ): {0}", - Buffer.GetByte( arr, 26 ) ); + Console.WriteLine("Final values of array:\n"); + DisplayArray(arr); + Console.WriteLine($"\nBuffer.GetByte( arr, 26 ): {Buffer.GetByte(arr, 26)}"); } } diff --git a/snippets/csharp/System/Buffer/Overview/overlap1.cs b/snippets/csharp/System/Buffer/Overview/overlap1.cs index 6cdc0acd694..17c02cbff19 100644 --- a/snippets/csharp/System/Buffer/Overview/overlap1.cs +++ b/snippets/csharp/System/Buffer/Overview/overlap1.cs @@ -2,36 +2,36 @@ public class Example { - public static void Main() - { - CopyUp(); - Console.WriteLine(); - CopyDown(); - } + public static void Main() + { + CopyUp(); + Console.WriteLine(); + CopyDown(); + } - private static void CopyUp() - { - // - const int INT_SIZE = 4; - int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; - Buffer.BlockCopy(arr, 0 * INT_SIZE, arr, 3 * INT_SIZE, 4 * INT_SIZE); - foreach (int value in arr) - Console.Write("{0} ", value); - // The example displays the following output: - // 2 4 6 2 4 6 8 16 18 20 - // - } + private static void CopyUp() + { + // + const int INT_SIZE = 4; + int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; + Buffer.BlockCopy(arr, 0 * INT_SIZE, arr, 3 * INT_SIZE, 4 * INT_SIZE); + foreach (int value in arr) + Console.Write($"{value} "); + // The example displays the following output: + // 2 4 6 2 4 6 8 16 18 20 + // + } - private static void CopyDown() - { - // - const int INT_SIZE = 4; - int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; - Buffer.BlockCopy(arr, 3 * INT_SIZE, arr, 0 * INT_SIZE, 4 * INT_SIZE); - foreach (int value in arr) - Console.Write("{0} ", value); - // The example displays the following output: - // 8 10 12 14 10 12 14 16 18 20 - // - } + private static void CopyDown() + { + // + const int INT_SIZE = 4; + int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; + Buffer.BlockCopy(arr, 3 * INT_SIZE, arr, 0 * INT_SIZE, 4 * INT_SIZE); + foreach (int value in arr) + Console.Write($"{value} "); + // The example displays the following output: + // 8 10 12 14 10 12 14 16 18 20 + // + } } diff --git a/snippets/csharp/System/Byte/CompareTo/systembyte.cs b/snippets/csharp/System/Byte/CompareTo/systembyte.cs index dddbaf44645..7f3a315b644 100644 --- a/snippets/csharp/System/Byte/CompareTo/systembyte.cs +++ b/snippets/csharp/System/Byte/CompareTo/systembyte.cs @@ -2,111 +2,108 @@ namespace SystemByte_Examples { - /// - /// Summary description for Class1. - /// - class Class1 - { - static void Main(string[] args) - { - SystemByteExamples sbe = new SystemByteExamples(); - int numberToSet; - Byte compareByte; -// String stringToConvert; - - numberToSet = 120; -// stringToConvert = "200"; - compareByte = 201; - - sbe.MinMaxFields(numberToSet); - sbe.ParseByte(); - - sbe.Compare(compareByte); - } - } - - class SystemByteExamples - { - private Byte MemberByte; - - // c'tor() - public SystemByteExamples() - { - MemberByte = 0; - } - - // The following example demonstrates using the MinValue and MaxValue fields to - // determine whether an integer value falls within range of a byte. If it does, - // the value is set. If not, an error message is displayed. - - // MemberByte is assumed to exist as a class member. - - // - public void MinMaxFields(int numberToSet) - { - if(numberToSet <= (int)Byte.MaxValue && numberToSet >= (int)Byte.MinValue) - { - // You must explicitly convert an integer to a byte. - MemberByte = (Byte)numberToSet; - - // Displays MemberByte using the ToString() method. - Console.WriteLine("The MemberByte value is {0}", MemberByte.ToString()); - } - else - { - Console.WriteLine("The value {0} is outside of the range of possible Byte values", numberToSet.ToString()); - } - } - // - - // The following example converts the string representation of a byte - // into its actual numeric value. - - // MemberByte is assumed to exist as a class member. - - public void ParseByte() - { - // - string stringToConvert = " 162"; - byte byteValue; - - try - { - byteValue = Byte.Parse(stringToConvert); - Console.WriteLine("The byte value is {0}.", byteValue.ToString()); - } - catch(System.OverflowException e) - { - Console.WriteLine("Exception: {0}", e.Message); - } - // - } - - // The following example checks to see whether a byte passed in is - // greater than, less than, or equal to the member byte. - - // MemberByte is assumed to exist as a class member. - - // - public void Compare(Byte myByte) - { - int myCompareResult; - - myCompareResult = MemberByte.CompareTo(myByte); - - if(myCompareResult > 0) - { - Console.WriteLine("{0} is less than the MemberByte value {1}", myByte.ToString(), MemberByte.ToString()); - } - else if(myCompareResult < 0) - { - Console.WriteLine("{0} is greater than the MemberByte value {1}", myByte.ToString(), MemberByte.ToString()); - } - else - { - Console.WriteLine("{0} is equal to the MemberByte value {1}", myByte.ToString(), MemberByte.ToString()); - } - } - // - } + /// + /// Summary description for Class1. + /// + class Class1 + { + static void Main(string[] args) + { + SystemByteExamples sbe = new(); + int numberToSet; + byte compareByte; + // String stringToConvert; + + numberToSet = 120; + // stringToConvert = "200"; + compareByte = 201; + + sbe.MinMaxFields(numberToSet); + sbe.ParseByte(); + + sbe.Compare(compareByte); + } + } + + class SystemByteExamples + { + private byte MemberByte; + + // c'tor() + public SystemByteExamples() => MemberByte = 0; + + // The following example demonstrates using the MinValue and MaxValue fields to + // determine whether an integer value falls within range of a byte. If it does, + // the value is set. If not, an error message is displayed. + + // MemberByte is assumed to exist as a class member. + + // + public void MinMaxFields(int numberToSet) + { + if (numberToSet <= (int)byte.MaxValue && numberToSet >= (int)byte.MinValue) + { + // You must explicitly convert an integer to a byte. + MemberByte = (byte)numberToSet; + + // Displays MemberByte using the ToString() method. + Console.WriteLine($"The MemberByte value is {MemberByte.ToString()}"); + } + else + { + Console.WriteLine($"The value {numberToSet.ToString()} is outside of the range of possible Byte values"); + } + } + // + + // The following example converts the string representation of a byte + // into its actual numeric value. + + // MemberByte is assumed to exist as a class member. + + public void ParseByte() + { + // + string stringToConvert = " 162"; + byte byteValue; + + try + { + byteValue = byte.Parse(stringToConvert); + Console.WriteLine($"The byte value is {byteValue.ToString()}."); + } + catch (System.OverflowException e) + { + Console.WriteLine($"Exception: {e.Message}"); + } + // + } + + // The following example checks to see whether a byte passed in is + // greater than, less than, or equal to the member byte. + + // MemberByte is assumed to exist as a class member. + + // + public void Compare(byte myByte) + { + int myCompareResult; + + myCompareResult = MemberByte.CompareTo(myByte); + + if (myCompareResult > 0) + { + Console.WriteLine($"{myByte.ToString()} is less than the MemberByte value {MemberByte.ToString()}"); + } + else if (myCompareResult < 0) + { + Console.WriteLine($"{myByte.ToString()} is greater than the MemberByte value {MemberByte.ToString()}"); + } + else + { + Console.WriteLine($"{myByte.ToString()} is equal to the MemberByte value {MemberByte.ToString()}"); + } + } + // + } } diff --git a/snippets/csharp/System/Byte/Equals/eq.cs b/snippets/csharp/System/Byte/Equals/eq.cs index 80f430f5c4c..0d40fea6f33 100644 --- a/snippets/csharp/System/Byte/Equals/eq.cs +++ b/snippets/csharp/System/Byte/Equals/eq.cs @@ -8,14 +8,13 @@ class Sample { public static void Main() { - byte byteVal1 = 0x7f; - byte byteVal2 = 127; - object objectVal3 = byteVal2; -// - Console.WriteLine("byteVal1 = {0}, byteVal2 = {1}, objectVal3 = {2}\n", - byteVal1, byteVal2, objectVal3); - Console.WriteLine("byteVal1 equals byteVal2?: {0}", byteVal1.Equals(byteVal2)); - Console.WriteLine("byteVal1 equals objectVal3?: {0}", byteVal1.Equals(objectVal3)); + byte byteVal1 = 0x7f; + byte byteVal2 = 127; + object objectVal3 = byteVal2; + // + Console.WriteLine($"byteVal1 = {byteVal1}, byteVal2 = {byteVal2}, objectVal3 = {objectVal3}\n"); + Console.WriteLine($"byteVal1 equals byteVal2?: {byteVal1.Equals(byteVal2)}"); + Console.WriteLine($"byteVal1 equals objectVal3?: {byteVal1.Equals(objectVal3)}"); } } @@ -28,4 +27,4 @@ public static void Main() byteVal1 equals objectVal3?: True */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Byte/Overview/ToByte5.cs b/snippets/csharp/System/Byte/Overview/ToByte5.cs index 74f608ed14a..36f35fb8b7a 100644 --- a/snippets/csharp/System/Byte/Overview/ToByte5.cs +++ b/snippets/csharp/System/Byte/Overview/ToByte5.cs @@ -3,26 +3,28 @@ public class Example5 { - public static void Main() - { - String[] values = { null, "", "0xC9", "C9", "101", "16.3", + public static void Main() + { + string[] values = { null, "", "0xC9", "C9", "101", "16.3", "$12", "$12.01", "-4", "1,032", "255", " 16 " }; - foreach (var value in values) { - try { - byte number = Convert.ToByte(value); - Console.WriteLine("'{0}' --> {1}", - value == null ? "" : value, number); - } - catch (FormatException) { - Console.WriteLine("Bad Format: '{0}'", - value == null ? "" : value); - } - catch (OverflowException) { - Console.WriteLine("OverflowException: '{0}'", value); - } - } - } + foreach (string value in values) + { + try + { + byte number = Convert.ToByte(value); + Console.WriteLine($"'{(value == null ? "" : value)}' --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"Bad Format: '{(value == null ? "" : value)}'"); + } + catch (OverflowException) + { + Console.WriteLine($"OverflowException: '{value}'"); + } + } + } } // The example displays the following output: // '' --> 0 diff --git a/snippets/csharp/System/Byte/Overview/bitwise1.cs b/snippets/csharp/System/Byte/Overview/bitwise1.cs index b3266d2482e..2087a3bed30 100644 --- a/snippets/csharp/System/Byte/Overview/bitwise1.cs +++ b/snippets/csharp/System/Byte/Overview/bitwise1.cs @@ -1,21 +1,22 @@ -// +// using System; using System.Globalization; public class Example { - public static void Main() - { - string[] values = [ Convert.ToString(12, 16), + public static void Main() + { + string[] values = [ Convert.ToString(12, 16), Convert.ToString(123, 16), Convert.ToString(245, 16) ]; - byte mask = 0xFE; - foreach (string value in values) { - Byte byteValue = Byte.Parse(value, NumberStyles.AllowHexSpecifier); - Console.WriteLine($"{byteValue} And {mask} = {byteValue & mask}"); - } - } + byte mask = 0xFE; + foreach (string value in values) + { + byte byteValue = byte.Parse(value, NumberStyles.AllowHexSpecifier); + Console.WriteLine($"{byteValue} And {mask} = {byteValue & mask}"); + } + } } // The example displays the following output: // 12 And 254 = 12 diff --git a/snippets/csharp/System/Byte/Overview/bitwise2.cs b/snippets/csharp/System/Byte/Overview/bitwise2.cs index 685c2f82f34..d932a89160f 100644 --- a/snippets/csharp/System/Byte/Overview/bitwise2.cs +++ b/snippets/csharp/System/Byte/Overview/bitwise2.cs @@ -19,7 +19,7 @@ public static void Main() foreach (ByteString strValue in values) { - byte byteValue = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier); + byte byteValue = byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier); Console.WriteLine($"{strValue.Sign * byteValue} ({Convert.ToString(byteValue, 2)}) And {mask} ({Convert.ToString(mask, 2)}) = {(strValue.Sign & Math.Sign(mask)) * (byteValue & mask)} ({Convert.ToString(byteValue & mask, 2)})"); } } @@ -30,7 +30,7 @@ private static ByteString[] CreateArray(params int[] values) foreach (object value in values) { - ByteString temp = new ByteString(); + ByteString temp = new(); int sign = Math.Sign((int)value); temp.Sign = sign; diff --git a/snippets/csharp/System/Byte/Overview/byteinstantiation1.cs b/snippets/csharp/System/Byte/Overview/byteinstantiation1.cs index ef7211fc761..5a7f53a0ccf 100644 --- a/snippets/csharp/System/Byte/Overview/byteinstantiation1.cs +++ b/snippets/csharp/System/Byte/Overview/byteinstantiation1.cs @@ -54,7 +54,7 @@ private static void Parse() string string1 = "244"; try { - byte byte1 = Byte.Parse(string1); + byte byte1 = byte.Parse(string1); Console.WriteLine(byte1); } catch (OverflowException) @@ -69,7 +69,7 @@ private static void Parse() string string2 = "F9"; try { - byte byte2 = Byte.Parse(string2, + byte byte2 = byte.Parse(string2, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(byte2); } diff --git a/snippets/csharp/System/Byte/Overview/formatting1.cs b/snippets/csharp/System/Byte/Overview/formatting1.cs index 6f4d4710187..5d1bcad8a09 100644 --- a/snippets/csharp/System/Byte/Overview/formatting1.cs +++ b/snippets/csharp/System/Byte/Overview/formatting1.cs @@ -12,11 +12,11 @@ public static void Main() private static void CallToString() { // - byte[] numbers = [ 0, 16, 104, 213 ]; + byte[] numbers = [0, 16, 104, 213]; foreach (byte number in numbers) { // Display value using default formatting. - Console.Write("{0,-3} --> ", number.ToString()); + Console.Write($"{number.ToString(),-3} --> "); // Display value with 3 digits and leading zeros. Console.Write(number.ToString("D3") + " "); // Display value with hexadecimal. @@ -36,14 +36,10 @@ private static void CallConvert() { // byte[] numbers = { 0, 16, 104, 213 }; - Console.WriteLine("{0} {1,8} {2,5} {3,5}", - "Value", "Binary", "Octal", "Hex"); + Console.WriteLine($"{"Value"} {"Binary",8} {"Octal",5} {"Hex",5}"); foreach (byte number in numbers) { - Console.WriteLine("{0,5} {1,8} {2,5} {3,5}", - number, Convert.ToString(number, 2), - Convert.ToString(number, 8), - Convert.ToString(number, 16)); + Console.WriteLine($"{number,5} {Convert.ToString(number, 2),8} {Convert.ToString(number, 8),5} {Convert.ToString(number, 16),5}"); } // The example displays the following output: // Value Binary Octal Hex diff --git a/snippets/csharp/System/Byte/Overview/tobyte1.cs b/snippets/csharp/System/Byte/Overview/tobyte1.cs index bc260436d8c..de6255be0d7 100644 --- a/snippets/csharp/System/Byte/Overview/tobyte1.cs +++ b/snippets/csharp/System/Byte/Overview/tobyte1.cs @@ -2,300 +2,286 @@ public class Example1 { - public static void Main() - { - ConvertBoolean(); - Console.WriteLine("-----"); - ConvertChar(); - Console.WriteLine("-----"); - ConvertInt16(); - Console.WriteLine("-----"); - ConvertInt32(); - Console.WriteLine("-----"); - ConvertInt64(); - Console.WriteLine("-----"); - ConvertObject(); - Console.WriteLine("-----"); - ConvertSByte(); - Console.WriteLine("-----"); - ConvertUInt16(); - Console.WriteLine("-----"); - ConvertUInt32(); - Console.WriteLine("-----"); - ConvertUInt64(); - } - private static void ConvertBoolean() - { - // - bool falseFlag = false; - bool trueFlag = true; + public static void Main() + { + ConvertBoolean(); + Console.WriteLine("-----"); + ConvertChar(); + Console.WriteLine("-----"); + ConvertInt16(); + Console.WriteLine("-----"); + ConvertInt32(); + Console.WriteLine("-----"); + ConvertInt64(); + Console.WriteLine("-----"); + ConvertObject(); + Console.WriteLine("-----"); + ConvertSByte(); + Console.WriteLine("-----"); + ConvertUInt16(); + Console.WriteLine("-----"); + ConvertUInt32(); + Console.WriteLine("-----"); + ConvertUInt64(); + } + private static void ConvertBoolean() + { + // + bool falseFlag = false; + bool trueFlag = true; - Console.WriteLine("{0} converts to {1}.", falseFlag, - Convert.ToByte(falseFlag)); - Console.WriteLine("{0} converts to {1}.", trueFlag, - Convert.ToByte(trueFlag)); - // The example displays the following output: - // False converts to 0. - // True converts to 1. - // - } + Console.WriteLine($"{falseFlag} converts to {Convert.ToByte(falseFlag)}."); + Console.WriteLine($"{trueFlag} converts to {Convert.ToByte(trueFlag)}."); + // The example displays the following output: + // False converts to 0. + // True converts to 1. + // + } - private static void ConvertChar() - { - // - char[] chars = { 'a', 'z', '\x0007', '\x03FF' }; - foreach (char ch in chars) - { - try { - byte result = Convert.ToByte(ch); - Console.WriteLine("{0} is converted to {1}.", ch, result); - } - catch (OverflowException) { - Console.WriteLine("Unable to convert u+{0} to a byte.", - Convert.ToInt16(ch).ToString("X4")); - } - } - // The example displays the following output: - // a is converted to 97. - // z is converted to 122. - // is converted to 7. - // Unable to convert u+03FF to a byte. - // - } + private static void ConvertChar() + { + // + char[] chars = { 'a', 'z', '\x0007', '\x03FF' }; + foreach (char ch in chars) + { + try + { + byte result = Convert.ToByte(ch); + Console.WriteLine($"{ch} is converted to {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"Unable to convert u+{Convert.ToInt16(ch).ToString("X4")} to a byte."); + } + } + // The example displays the following output: + // a is converted to 97. + // z is converted to 122. + // is converted to 7. + // Unable to convert u+03FF to a byte. + // + } - private static void ConvertInt16() - { - // - short[] numbers = { Int16.MinValue, -1, 0, 121, 340, Int16.MaxValue }; - byte result; - foreach (short number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // The Int16 value -32768 is outside the range of the Byte type. - // The Int16 value -1 is outside the range of the Byte type. - // Converted the Int16 value 0 to the Byte value 0. - // Converted the Int16 value 121 to the Byte value 121. - // The Int16 value 340 is outside the range of the Byte type. - // The Int16 value 32767 is outside the range of the Byte type. - // - } + private static void ConvertInt16() + { + // + short[] numbers = { short.MinValue, -1, 0, 121, 340, short.MaxValue }; + byte result; + foreach (short number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // The Int16 value -32768 is outside the range of the Byte type. + // The Int16 value -1 is outside the range of the Byte type. + // Converted the Int16 value 0 to the Byte value 0. + // Converted the Int16 value 121 to the Byte value 121. + // The Int16 value 340 is outside the range of the Byte type. + // The Int16 value 32767 is outside the range of the Byte type. + // + } - private static void ConvertInt32() - { - // - int[] numbers = { Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue }; - byte result; - foreach (int number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // The Int32 value -2147483648 is outside the range of the Byte type. - // The Int32 value -1 is outside the range of the Byte type. - // Converted the Int32 value 0 to the Byte value 0. - // Converted the Int32 value 121 to the Byte value 121. - // The Int32 value 340 is outside the range of the Byte type. - // The Int32 value 2147483647 is outside the range of the Byte type. - // - } + private static void ConvertInt32() + { + // + int[] numbers = { int.MinValue, -1, 0, 121, 340, int.MaxValue }; + byte result; + foreach (int number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // The Int32 value -2147483648 is outside the range of the Byte type. + // The Int32 value -1 is outside the range of the Byte type. + // Converted the Int32 value 0 to the Byte value 0. + // Converted the Int32 value 121 to the Byte value 121. + // The Int32 value 340 is outside the range of the Byte type. + // The Int32 value 2147483647 is outside the range of the Byte type. + // + } - private static void ConvertInt64() - { - // - long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue }; - byte result; - foreach (long number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // The Int64 value -9223372036854775808 is outside the range of the Byte type. - // The Int64 value -1 is outside the range of the Byte type. - // Converted the Int64 value 0 to the Byte value 0. - // Converted the Int64 value 121 to the Byte value 121. - // The Int64 value 340 is outside the range of the Byte type. - // The Int64 value 9223372036854775807 is outside the range of the Byte type. - // - } + private static void ConvertInt64() + { + // + long[] numbers = { long.MinValue, -1, 0, 121, 340, long.MaxValue }; + byte result; + foreach (long number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // The Int64 value -9223372036854775808 is outside the range of the Byte type. + // The Int64 value -1 is outside the range of the Byte type. + // Converted the Int64 value 0 to the Byte value 0. + // Converted the Int64 value 121 to the Byte value 121. + // The Int64 value 340 is outside the range of the Byte type. + // The Int64 value 9223372036854775807 is outside the range of the Byte type. + // + } - private static void ConvertObject() - { - // - object[] values = { true, -12, 163, 935, 'x', "104", "103.0", "-1", + private static void ConvertObject() + { + // + object[] values = { true, -12, 163, 935, 'x', "104", "103.0", "-1", "1.00e2", "One", 1.00e2}; - byte result; - foreach (object value in values) - { - try { - result = Convert.ToByte(value); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); - } - catch (OverflowException) - { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - value.GetType().Name, value); - } - catch (FormatException) - { - Console.WriteLine("The {0} value {1} is not in a recognizable format.", - value.GetType().Name, value); - } - catch (InvalidCastException) - { - Console.WriteLine("No conversion to a Byte exists for the {0} value {1}.", - value.GetType().Name, value); - } - } - // The example displays the following output: - // Converted the Boolean value True to the Byte value 1. - // The Int32 value -12 is outside the range of the Byte type. - // Converted the Int32 value 163 to the Byte value 163. - // The Int32 value 935 is outside the range of the Byte type. - // Converted the Char value x to the Byte value 120. - // Converted the String value 104 to the Byte value 104. - // The String value 103.0 is not in a recognizable format. - // The String value -1 is outside the range of the Byte type. - // The String value 1.00e2 is not in a recognizable format. - // The String value One is not in a recognizable format. - // Converted the Double value 100 to the Byte value 100. - // - } + byte result; + foreach (object value in values) + { + try + { + result = Convert.ToByte(value); + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {value.GetType().Name} value {value} is outside the range of the Byte type."); + } + catch (FormatException) + { + Console.WriteLine($"The {value.GetType().Name} value {value} is not in a recognizable format."); + } + catch (InvalidCastException) + { + Console.WriteLine($"No conversion to a Byte exists for the {value.GetType().Name} value {value}."); + } + } + // The example displays the following output: + // Converted the Boolean value True to the Byte value 1. + // The Int32 value -12 is outside the range of the Byte type. + // Converted the Int32 value 163 to the Byte value 163. + // The Int32 value 935 is outside the range of the Byte type. + // Converted the Char value x to the Byte value 120. + // Converted the String value 104 to the Byte value 104. + // The String value 103.0 is not in a recognizable format. + // The String value -1 is outside the range of the Byte type. + // The String value 1.00e2 is not in a recognizable format. + // The String value One is not in a recognizable format. + // Converted the Double value 100 to the Byte value 100. + // + } - private static void ConvertSByte() - { - // - sbyte[] numbers = { SByte.MinValue, -1, 0, 10, SByte.MaxValue }; - byte result; - foreach (sbyte number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) - { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // The SByte value -128 is outside the range of the Byte type. - // The SByte value -1 is outside the range of the Byte type. - // Converted the SByte value 0 to the Byte value 0. - // Converted the SByte value 10 to the Byte value 10. - // Converted the SByte value 127 to the Byte value 127. - // - } + private static void ConvertSByte() + { + // + sbyte[] numbers = { sbyte.MinValue, -1, 0, 10, sbyte.MaxValue }; + byte result; + foreach (sbyte number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // The SByte value -128 is outside the range of the Byte type. + // The SByte value -1 is outside the range of the Byte type. + // Converted the SByte value 0 to the Byte value 0. + // Converted the SByte value 10 to the Byte value 10. + // Converted the SByte value 127 to the Byte value 127. + // + } - private static void ConvertUInt16() - { - // - ushort[] numbers = { UInt16.MinValue, 121, 340, UInt16.MaxValue }; - byte result; - foreach (ushort number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // Converted the UInt16 value 0 to the Byte value 0. - // Converted the UInt16 value 121 to the Byte value 121. - // The UInt16 value 340 is outside the range of the Byte type. - // The UInt16 value 65535 is outside the range of the Byte type. - // - } + private static void ConvertUInt16() + { + // + ushort[] numbers = { ushort.MinValue, 121, 340, ushort.MaxValue }; + byte result; + foreach (ushort number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // Converted the UInt16 value 0 to the Byte value 0. + // Converted the UInt16 value 121 to the Byte value 121. + // The UInt16 value 340 is outside the range of the Byte type. + // The UInt16 value 65535 is outside the range of the Byte type. + // + } - private static void ConvertUInt32() - { - // - uint[] numbers = { UInt32.MinValue, 121, 340, UInt32.MaxValue }; - byte result; - foreach (uint number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // Converted the UInt32 value 0 to the Byte value 0. - // Converted the UInt32 value 121 to the Byte value 121. - // The UInt32 value 340 is outside the range of the Byte type. - // The UInt32 value 4294967295 is outside the range of the Byte type. - // - } + private static void ConvertUInt32() + { + // + uint[] numbers = { uint.MinValue, 121, 340, uint.MaxValue }; + byte result; + foreach (uint number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // Converted the UInt32 value 0 to the Byte value 0. + // Converted the UInt32 value 121 to the Byte value 121. + // The UInt32 value 340 is outside the range of the Byte type. + // The UInt32 value 4294967295 is outside the range of the Byte type. + // + } - private static void ConvertUInt64() - { - // - ulong[] numbers= { UInt64.MinValue, 121, 340, UInt64.MaxValue }; - byte result; - foreach (ulong number in numbers) - { - try { - result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); - } - catch (OverflowException) - { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); - } - } - // The example displays the following output: - // Converted the UInt64 value 0 to the Byte value 0. - // Converted the UInt64 value 121 to the Byte value 121. - // The UInt64 value 340 is outside the range of the Byte type. - // The UInt64 value 18446744073709551615 is outside the range of the Byte type. - // - } + private static void ConvertUInt64() + { + // + ulong[] numbers = { ulong.MinValue, 121, 340, ulong.MaxValue }; + byte result; + foreach (ulong number in numbers) + { + try + { + result = Convert.ToByte(number); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); + } + catch (OverflowException) + { + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); + } + } + // The example displays the following output: + // Converted the UInt64 value 0 to the Byte value 0. + // Converted the UInt64 value 121 to the Byte value 121. + // The UInt64 value 340 is outside the range of the Byte type. + // The UInt64 value 18446744073709551615 is outside the range of the Byte type. + // + } } diff --git a/snippets/csharp/System/Byte/Overview/tobyte2.cs b/snippets/csharp/System/Byte/Overview/tobyte2.cs index 19b5a2296c8..929f7c77954 100644 --- a/snippets/csharp/System/Byte/Overview/tobyte2.cs +++ b/snippets/csharp/System/Byte/Overview/tobyte2.cs @@ -3,34 +3,37 @@ public class Example2 { - public static void Main() - { - int[] bases = { 2, 8, 10, 16 }; - string[] values = { "-1", "1", "08", "0F", "11" , "12", "30", + public static void Main() + { + int[] bases = { 2, 8, 10, 16 }; + string[] values = { "-1", "1", "08", "0F", "11" , "12", "30", "101", "255", "FF", "10000000", "80" }; - byte number; - foreach (int numBase in bases) - { - Console.WriteLine("Base {0}:", numBase); - foreach (string value in values) - { - try { - number = Convert.ToByte(value, numBase); - Console.WriteLine(" Converted '{0}' to {1}.", value, number); + byte number; + foreach (int numBase in bases) + { + Console.WriteLine($"Base {numBase}:"); + foreach (string value in values) + { + try + { + number = Convert.ToByte(value, numBase); + Console.WriteLine($" Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($" '{value}' is not in the correct format for a base {numBase} byte value."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is outside the range of the Byte type."); + } + catch (ArgumentException) + { + Console.WriteLine($" '{value}' is invalid in base {numBase}."); + } } - catch (FormatException) { - Console.WriteLine(" '{0}' is not in the correct format for a base {1} byte value.", - value, numBase); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is outside the range of the Byte type.", value); - } - catch (ArgumentException) { - Console.WriteLine(" '{0}' is invalid in base {1}.", value, numBase); - } - } - } - } + } + } } // The example displays the following output: diff --git a/snippets/csharp/System/Byte/Overview/tobyte3.cs b/snippets/csharp/System/Byte/Overview/tobyte3.cs index 037bb62aa29..aea56b403b4 100644 --- a/snippets/csharp/System/Byte/Overview/tobyte3.cs +++ b/snippets/csharp/System/Byte/Overview/tobyte3.cs @@ -2,243 +2,244 @@ using System; using System.Globalization; -public enum SignBit { Negative=-1, Zero=0, Positive=1 }; +public enum SignBit { Negative = -1, Zero = 0, Positive = 1 }; public struct ByteString3 : IConvertible { - private SignBit signBit; - private string byteString; + private SignBit signBit; + private string byteString; - public SignBit Sign + public SignBit Sign { - set { signBit = value; } - get { return signBit; } + set => signBit = value; + get => signBit; } - public string Value - { - set { - if (value.Trim().Length > 2) - throw new ArgumentException("The string representation of a byte cannot have more than two characters."); - else - byteString = value; - } - get { return byteString; } - } - - // IConvertible implementations. - public TypeCode GetTypeCode() { - return TypeCode.Object; - } - - public bool ToBoolean(IFormatProvider provider) - { - if (signBit == SignBit.Zero) - return false; - else - return true; - } - - public byte ToByte(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - throw new OverflowException(String.Format("{0} is out of range of the Byte type.", Convert.ToSByte(byteString, 16))); - else - return Byte.Parse(byteString, NumberStyles.HexNumber); - } - - public char ToChar(IFormatProvider provider) - { - if (signBit == SignBit.Negative) { - throw new OverflowException(String.Format("{0} is out of range of the Char type.", Convert.ToSByte(byteString, 16))); - } - else { - byte byteValue = Byte.Parse(this.byteString, NumberStyles.HexNumber); - return Convert.ToChar(byteValue); - } - } - - public DateTime ToDateTime(IFormatProvider provider) - { - throw new InvalidCastException("ByteString3 to DateTime conversion is not supported."); - } - - public decimal ToDecimal(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - { - sbyte byteValue = SByte.Parse(byteString, NumberStyles.HexNumber); - return Convert.ToDecimal(byteValue); - } - else - { - byte byteValue = Byte.Parse(byteString, NumberStyles.HexNumber); - return Convert.ToDecimal(byteValue); - } - } - - public double ToDouble(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - return Convert.ToDouble(SByte.Parse(byteString, NumberStyles.HexNumber)); - else - return Convert.ToDouble(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public short ToInt16(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - return Convert.ToInt16(SByte.Parse(byteString, NumberStyles.HexNumber)); - else - return Convert.ToInt16(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public int ToInt32(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - return Convert.ToInt32(SByte.Parse(byteString, NumberStyles.HexNumber)); - else - return Convert.ToInt32(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public long ToInt64(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - return Convert.ToInt64(SByte.Parse(byteString, NumberStyles.HexNumber)); - else - return Convert.ToInt64(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public sbyte ToSByte(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - try { - return Convert.ToSByte(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - catch (OverflowException e) { - throw new OverflowException(String.Format("{0} is outside the range of the SByte type.", - Byte.Parse(byteString, NumberStyles.HexNumber)), e); - } - else - return SByte.Parse(byteString, NumberStyles.HexNumber); - } - - public float ToSingle(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - return Convert.ToSingle(SByte.Parse(byteString, NumberStyles.HexNumber)); - else - return Convert.ToSingle(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public string ToString(IFormatProvider provider) - { - return "0x" + this.byteString; - } - - public object ToType(Type conversionType, IFormatProvider provider) - { - switch (Type.GetTypeCode(conversionType)) - { - case TypeCode.Boolean: - return this.ToBoolean(null); - case TypeCode.Byte: - return this.ToByte(null); - case TypeCode.Char: - return this.ToChar(null); - case TypeCode.DateTime: - return this.ToDateTime(null); - case TypeCode.Decimal: - return this.ToDecimal(null); - case TypeCode.Double: - return this.ToDouble(null); - case TypeCode.Int16: - return this.ToInt16(null); - case TypeCode.Int32: - return this.ToInt32(null); - case TypeCode.Int64: - return this.ToInt64(null); - case TypeCode.Object: - if (typeof(ByteString3).Equals(conversionType)) - return this; + public string Value + { + set + { + if (value.Trim().Length > 2) + throw new ArgumentException("The string representation of a byte cannot have more than two characters."); else - throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.", conversionType.Name)); - case TypeCode.SByte: - return this.ToSByte(null); - case TypeCode.Single: - return this.ToSingle(null); - case TypeCode.String: - return this.ToString(null); - case TypeCode.UInt16: - return this.ToUInt16(null); - case TypeCode.UInt32: - return this.ToUInt32(null); - case TypeCode.UInt64: - return this.ToUInt64(null); - default: - throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name)); - } - } - - public UInt16 ToUInt16(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - throw new OverflowException(String.Format("{0} is outside the range of the UInt16 type.", - SByte.Parse(byteString, NumberStyles.HexNumber))); - else - return Convert.ToUInt16(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public UInt32 ToUInt32(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - throw new OverflowException(String.Format("{0} is outside the range of the UInt32 type.", - SByte.Parse(byteString, NumberStyles.HexNumber))); - else - return Convert.ToUInt32(Byte.Parse(byteString, NumberStyles.HexNumber)); - } - - public UInt64 ToUInt64(IFormatProvider provider) - { - if (signBit == SignBit.Negative) - throw new OverflowException(String.Format("{0} is outside the range of the UInt64 type.", - SByte.Parse(byteString, NumberStyles.HexNumber))); - else - return Convert.ToUInt64(Byte.Parse(byteString, NumberStyles.HexNumber)); - } + byteString = value; + } + get => byteString; + } + + // IConvertible implementations. + public TypeCode GetTypeCode() => TypeCode.Object; + + public bool ToBoolean(IFormatProvider provider) + { + if (signBit == SignBit.Zero) + return false; + else + return true; + } + + public byte ToByte(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + throw new OverflowException($"{Convert.ToSByte(byteString, 16)} is out of range of the Byte type."); + else + return byte.Parse(byteString, NumberStyles.HexNumber); + } + + public char ToChar(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + { + throw new OverflowException($"{Convert.ToSByte(byteString, 16)} is out of range of the Char type."); + } + else + { + byte byteValue = byte.Parse(this.byteString, NumberStyles.HexNumber); + return Convert.ToChar(byteValue); + } + } + + public DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException("ByteString3 to DateTime conversion is not supported."); + + public decimal ToDecimal(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + { + sbyte byteValue = sbyte.Parse(byteString, NumberStyles.HexNumber); + return Convert.ToDecimal(byteValue); + } + else + { + byte byteValue = byte.Parse(byteString, NumberStyles.HexNumber); + return Convert.ToDecimal(byteValue); + } + } + + public double ToDouble(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + return Convert.ToDouble(sbyte.Parse(byteString, NumberStyles.HexNumber)); + else + return Convert.ToDouble(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public short ToInt16(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + return Convert.ToInt16(sbyte.Parse(byteString, NumberStyles.HexNumber)); + else + return Convert.ToInt16(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public int ToInt32(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + return Convert.ToInt32(sbyte.Parse(byteString, NumberStyles.HexNumber)); + else + return Convert.ToInt32(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public long ToInt64(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + return Convert.ToInt64(sbyte.Parse(byteString, NumberStyles.HexNumber)); + else + return Convert.ToInt64(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public sbyte ToSByte(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + try + { + return Convert.ToSByte(byte.Parse(byteString, NumberStyles.HexNumber)); + } + catch (OverflowException e) + { + throw new OverflowException($"{byte.Parse(byteString, NumberStyles.HexNumber)} is outside the range of the SByte type.", e); + } + else + return sbyte.Parse(byteString, NumberStyles.HexNumber); + } + + public float ToSingle(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + return Convert.ToSingle(sbyte.Parse(byteString, NumberStyles.HexNumber)); + else + return Convert.ToSingle(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public string ToString(IFormatProvider provider) => "0x" + this.byteString; + + public object ToType(Type conversionType, IFormatProvider provider) + { + switch (Type.GetTypeCode(conversionType)) + { + case TypeCode.Boolean: + return this.ToBoolean(null); + case TypeCode.Byte: + return this.ToByte(null); + case TypeCode.Char: + return this.ToChar(null); + case TypeCode.DateTime: + return this.ToDateTime(null); + case TypeCode.Decimal: + return this.ToDecimal(null); + case TypeCode.Double: + return this.ToDouble(null); + case TypeCode.Int16: + return this.ToInt16(null); + case TypeCode.Int32: + return this.ToInt32(null); + case TypeCode.Int64: + return this.ToInt64(null); + case TypeCode.Object: + if (typeof(ByteString3).Equals(conversionType)) + return this; + else + throw new InvalidCastException($"Conversion to a {conversionType.Name} is not supported."); + case TypeCode.SByte: + return this.ToSByte(null); + case TypeCode.Single: + return this.ToSingle(null); + case TypeCode.String: + return this.ToString(null); + case TypeCode.UInt16: + return this.ToUInt16(null); + case TypeCode.UInt32: + return this.ToUInt32(null); + case TypeCode.UInt64: + return this.ToUInt64(null); + default: + throw new InvalidCastException($"Conversion to {conversionType.Name} is not supported."); + } + } + + public ushort ToUInt16(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + throw new OverflowException($"{sbyte.Parse(byteString, NumberStyles.HexNumber)} is outside the range of the UInt16 type."); + else + return Convert.ToUInt16(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public uint ToUInt32(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + throw new OverflowException($"{sbyte.Parse(byteString, NumberStyles.HexNumber)} is outside the range of the UInt32 type."); + else + return Convert.ToUInt32(byte.Parse(byteString, NumberStyles.HexNumber)); + } + + public ulong ToUInt64(IFormatProvider provider) + { + if (signBit == SignBit.Negative) + throw new OverflowException($"{sbyte.Parse(byteString, NumberStyles.HexNumber)} is outside the range of the UInt64 type."); + else + return Convert.ToUInt64(byte.Parse(byteString, NumberStyles.HexNumber)); + } } // // public class Class1 { - public static void Main() - { - byte positiveByte = 216; - sbyte negativeByte = -101; - - ByteString3 positiveString = new ByteString3(); - positiveString.Sign = (SignBit) Math.Sign(positiveByte); - positiveString.Value = positiveByte.ToString("X2"); - - ByteString3 negativeString = new ByteString3(); - negativeString.Sign = (SignBit) Math.Sign(negativeByte); - negativeString.Value = negativeByte.ToString("X2"); - - try { - Console.WriteLine("'{0}' converts to {1}.", positiveString.Value, Convert.ToByte(positiveString)); - } - catch (OverflowException) { - Console.WriteLine("0x{0} is outside the range of the Byte type.", positiveString.Value); - } - - try { - Console.WriteLine("'{0}' converts to {1}.", negativeString.Value, Convert.ToByte(negativeString)); - } - catch (OverflowException) { - Console.WriteLine("0x{0} is outside the range of the Byte type.", negativeString.Value); - } - } + public static void Main() + { + byte positiveByte = 216; + sbyte negativeByte = -101; + + ByteString3 positiveString = new() + { + Sign = (SignBit)Math.Sign(positiveByte), + Value = positiveByte.ToString("X2") + }; + + ByteString3 negativeString = new() + { + Sign = (SignBit)Math.Sign(negativeByte), + Value = negativeByte.ToString("X2") + }; + + try + { + Console.WriteLine($"'{positiveString.Value}' converts to {Convert.ToByte(positiveString)}."); + } + catch (OverflowException) + { + Console.WriteLine($"0x{positiveString.Value} is outside the range of the Byte type."); + } + + try + { + Console.WriteLine($"'{negativeString.Value}' converts to {Convert.ToByte(negativeString)}."); + } + catch (OverflowException) + { + Console.WriteLine($"0x{negativeString.Value} is outside the range of the Byte type."); + } + } } // The example displays the following output: // 'D8' converts to 216. diff --git a/snippets/csharp/System/Byte/Overview/tobyte4.cs b/snippets/csharp/System/Byte/Overview/tobyte4.cs index cb1ef5c8c9c..3236b38a000 100644 --- a/snippets/csharp/System/Byte/Overview/tobyte4.cs +++ b/snippets/csharp/System/Byte/Overview/tobyte4.cs @@ -4,39 +4,42 @@ public class Example4 { - public static void Main() - { - // Create a NumberFormatInfo object and set several of its - // properties that apply to unsigned bytes. - NumberFormatInfo provider = new NumberFormatInfo(); + public static void Main() + { + // Create a NumberFormatInfo object and set several of its + // properties that apply to unsigned bytes. + NumberFormatInfo provider = new(); - // These properties affect the conversion. - provider.PositiveSign = "pos "; - provider.NegativeSign = "neg "; + // These properties affect the conversion. + provider.PositiveSign = "pos "; + provider.NegativeSign = "neg "; - // This property does not affect the conversion. - // The input string cannot have a decimal separator. - provider.NumberDecimalSeparator = "."; + // This property does not affect the conversion. + // The input string cannot have a decimal separator. + provider.NumberDecimalSeparator = "."; - // Define an array of numeric strings. - string[] numericStrings = { "234", "+234", "pos 234", "234.", "255", + // Define an array of numeric strings. + string[] numericStrings = { "234", "+234", "pos 234", "234.", "255", "256", "-1" }; - foreach (string numericString in numericStrings) - { - Console.Write("'{0,-8}' -> ", numericString); - try { - byte number = Convert.ToByte(numericString, provider); - Console.WriteLine(number); - } - catch (FormatException) { - Console.WriteLine("Incorrect Format"); - } - catch (OverflowException) { - Console.WriteLine("Overflows a Byte"); - } - } - } + foreach (string numericString in numericStrings) + { + Console.Write($"'{numericString,-8}' -> "); + try + { + byte number = Convert.ToByte(numericString, provider); + Console.WriteLine(number); + } + catch (FormatException) + { + Console.WriteLine("Incorrect Format"); + } + catch (OverflowException) + { + Console.WriteLine("Overflows a Byte"); + } + } + } } // The example displays the following output: // '234 ' -> 234 diff --git a/snippets/csharp/System/Byte/Parse/parse.cs b/snippets/csharp/System/Byte/Parse/parse.cs index 492a1c3aa3d..bcb0d06282f 100644 --- a/snippets/csharp/System/Byte/Parse/parse.cs +++ b/snippets/csharp/System/Byte/Parse/parse.cs @@ -3,153 +3,168 @@ public class Class1 { - public static void Main() - { - CallParse1(); - Console.WriteLine(); - CallParse2(); - Console.WriteLine(); - CallParse3(); - Console.WriteLine(); - CallParse4(); - } + public static void Main() + { + CallParse1(); + Console.WriteLine(); + CallParse2(); + Console.WriteLine(); + CallParse3(); + Console.WriteLine(); + CallParse4(); + } - private static void CallParse1() - { - // - string stringToConvert = " 162"; - byte byteValue; - try - { - byteValue = Byte.Parse(stringToConvert); - Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, byteValue); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}'.", stringToConvert); - } - catch (OverflowException) - { - Console.WriteLine("'{0}' is greater than {1} or less than {2}.", - stringToConvert, Byte.MaxValue, Byte.MinValue); - } - // The example displays the following output to the console: - // Converted ' 162' to 162. - // - } + private static void CallParse1() + { + // + string stringToConvert = " 162"; + byte byteValue; + try + { + byteValue = byte.Parse(stringToConvert); + Console.WriteLine($"Converted '{stringToConvert}' to {byteValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{stringToConvert}'."); + } + catch (OverflowException) + { + Console.WriteLine($"'{stringToConvert}' is greater than {byte.MaxValue} or less than {byte.MinValue}."); + } + // The example displays the following output to the console: + // Converted ' 162' to 162. + // + } - private static void CallParse2() - { - // - string stringToConvert; - byte byteValue; + private static void CallParse2() + { + // + string stringToConvert; + byte byteValue; - stringToConvert = " 214 "; - try { - byteValue = Byte.Parse(stringToConvert, CultureInfo.InvariantCulture); - Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, byteValue); - } - catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'.", stringToConvert); } - catch (OverflowException) { - Console.WriteLine("'{0}' is greater than {1} or less than {2}.", - stringToConvert, Byte.MaxValue, Byte.MinValue); } + stringToConvert = " 214 "; + try + { + byteValue = byte.Parse(stringToConvert, CultureInfo.InvariantCulture); + Console.WriteLine($"Converted '{stringToConvert}' to {byteValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{stringToConvert}'."); + } + catch (OverflowException) + { + Console.WriteLine($"'{stringToConvert}' is greater than {byte.MaxValue} or less than {byte.MinValue}."); + } - stringToConvert = " + 214 "; - try { - byteValue = Byte.Parse(stringToConvert, CultureInfo.InvariantCulture); - Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, byteValue); - } - catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'.", stringToConvert); } - catch (OverflowException) { - Console.WriteLine("'{0}' is greater than {1} or less than {2}.", - stringToConvert, Byte.MaxValue, Byte.MinValue); } + stringToConvert = " + 214 "; + try + { + byteValue = byte.Parse(stringToConvert, CultureInfo.InvariantCulture); + Console.WriteLine($"Converted '{stringToConvert}' to {byteValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{stringToConvert}'."); + } + catch (OverflowException) + { + Console.WriteLine($"'{stringToConvert}' is greater than {byte.MaxValue} or less than {byte.MinValue}."); + } - stringToConvert = " +214 "; - try { - byteValue = Byte.Parse(stringToConvert, CultureInfo.InvariantCulture); - Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, byteValue); - } - catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'.", stringToConvert); } - catch (OverflowException) { - Console.WriteLine("'{0}' is greater than {1} or less than {2}.", - stringToConvert, Byte.MaxValue, Byte.MinValue); } - // The example displays the following output to the console: - // Converted ' 214 ' to 214. - // Unable to parse ' + 214 '. - // Converted ' +214 ' to 214. - // - } - private static void CallParse3() - { - // - string value; - NumberStyles style; - byte number; + stringToConvert = " +214 "; + try + { + byteValue = byte.Parse(stringToConvert, CultureInfo.InvariantCulture); + Console.WriteLine($"Converted '{stringToConvert}' to {byteValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{stringToConvert}'."); + } + catch (OverflowException) + { + Console.WriteLine($"'{stringToConvert}' is greater than {byte.MaxValue} or less than {byte.MinValue}."); + } + // The example displays the following output to the console: + // Converted ' 214 ' to 214. + // Unable to parse ' + 214 '. + // Converted ' +214 ' to 214. + // + } + private static void CallParse3() + { + // + string value; + NumberStyles style; + byte number; - // Parse value with no styles allowed. - style = NumberStyles.None; - value = " 241 "; - try - { - number = Byte.Parse(value, style); - Console.WriteLine("Converted '{0}' to {1}.", value, number); - } - catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'.", value); } + // Parse value with no styles allowed. + style = NumberStyles.None; + value = " 241 "; + try + { + number = byte.Parse(value, style); + Console.WriteLine($"Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } - // Parse value with trailing sign. - style = NumberStyles.Integer | NumberStyles.AllowTrailingSign; - value = " 163+"; - number = Byte.Parse(value, style); - Console.WriteLine("Converted '{0}' to {1}.", value, number); + // Parse value with trailing sign. + style = NumberStyles.Integer | NumberStyles.AllowTrailingSign; + value = " 163+"; + number = byte.Parse(value, style); + Console.WriteLine($"Converted '{value}' to {number}."); - // Parse value with leading sign. - value = " +253 "; - number = Byte.Parse(value, style); - Console.WriteLine("Converted '{0}' to {1}.", value, number); - // This example displays the following output to the console: - // Unable to parse ' 241 '. - // Converted ' 163+' to 163. - // Converted ' +253 ' to 253. - // - } + // Parse value with leading sign. + value = " +253 "; + number = byte.Parse(value, style); + Console.WriteLine($"Converted '{value}' to {number}."); + // This example displays the following output to the console: + // Unable to parse ' 241 '. + // Converted ' 163+' to 163. + // Converted ' +253 ' to 253. + // + } - private static void CallParse4() - { - // - NumberStyles style; - CultureInfo culture; - string value; - byte number; + private static void CallParse4() + { + // + NumberStyles style; + CultureInfo culture; + string value; + byte number; - // Parse number with decimals. - // NumberStyles.Float includes NumberStyles.AllowDecimalPoint. - style = NumberStyles.Float; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - value = "12,000"; + // Parse number with decimals. + // NumberStyles.Float includes NumberStyles.AllowDecimalPoint. + style = NumberStyles.Float; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + value = "12,000"; - number = Byte.Parse(value, style, culture); - Console.WriteLine("Converted '{0}' to {1}.", value, number); + number = byte.Parse(value, style, culture); + Console.WriteLine($"Converted '{value}' to {number}."); - culture = CultureInfo.CreateSpecificCulture("en-GB"); - try - { - number = Byte.Parse(value, style, culture); - Console.WriteLine("Converted '{0}' to {1}.", value, number); - } - catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'.", value); } + culture = CultureInfo.CreateSpecificCulture("en-GB"); + try + { + number = byte.Parse(value, style, culture); + Console.WriteLine($"Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } - value = "12.000"; - number = Byte.Parse(value, style, culture); - Console.WriteLine("Converted '{0}' to {1}.", value, number); - // The example displays the following output to the console: - // Converted '12,000' to 12. - // Unable to parse '12,000'. - // Converted '12.000' to 12. - // - } + value = "12.000"; + number = byte.Parse(value, style, culture); + Console.WriteLine($"Converted '{value}' to {number}."); + // The example displays the following output to the console: + // Converted '12,000' to 12. + // Unable to parse '12,000'. + // Converted '12.000' to 12. + // + } } diff --git a/snippets/csharp/System/Byte/ToString/NewByteMembers.cs b/snippets/csharp/System/Byte/ToString/NewByteMembers.cs index 4adede6123e..26b20304058 100644 --- a/snippets/csharp/System/Byte/ToString/NewByteMembers.cs +++ b/snippets/csharp/System/Byte/ToString/NewByteMembers.cs @@ -3,100 +3,97 @@ public class Class1 { - public static void Main() - { - CallToString(); - Console.WriteLine(); - SpecifyFormatProvider(); - Console.WriteLine(); - SpecifyFormatString(); - Console.WriteLine(); - FormatWithProviders(); - } + public static void Main() + { + CallToString(); + Console.WriteLine(); + SpecifyFormatProvider(); + Console.WriteLine(); + SpecifyFormatString(); + Console.WriteLine(); + FormatWithProviders(); + } - private static void CallToString() - { - // - byte[] bytes = {0, 1, 14, 168, 255}; - foreach (byte byteValue in bytes) - Console.WriteLine(byteValue); - // The example displays the following output to the console if the current - // culture is en-US: - // 0 - // 1 - // 14 - // 168 - // 255 - // - } + private static void CallToString() + { + // + byte[] bytes = { 0, 1, 14, 168, 255 }; + foreach (byte byteValue in bytes) + Console.WriteLine(byteValue); + // The example displays the following output to the console if the current + // culture is en-US: + // 0 + // 1 + // 14 + // 168 + // 255 + // + } - private static void SpecifyFormatProvider() - { - // - byte[] bytes = {0, 1, 14, 168, 255}; - CultureInfo[] providers = {new CultureInfo("en-us"), + private static void SpecifyFormatProvider() + { + // + byte[] bytes = { 0, 1, 14, 168, 255 }; + CultureInfo[] providers = {new CultureInfo("en-us"), new CultureInfo("fr-fr"), new CultureInfo("de-de"), new CultureInfo("es-es")}; - foreach (byte byteValue in bytes) - { - foreach (CultureInfo provider in providers) - Console.Write("{0,3} ({1}) ", - byteValue.ToString(provider), provider.Name); + foreach (byte byteValue in bytes) + { + foreach (CultureInfo provider in providers) + Console.Write($"{byteValue.ToString(provider),3} ({provider.Name}) "); - Console.WriteLine(); - } - // The example displays the following output to the console: - // 0 (en-US) 0 (fr-FR) 0 (de-DE) 0 (es-ES) - // 1 (en-US) 1 (fr-FR) 1 (de-DE) 1 (es-ES) - // 14 (en-US) 14 (fr-FR) 14 (de-DE) 14 (es-ES) - // 168 (en-US) 168 (fr-FR) 168 (de-DE) 168 (es-ES) - // 255 (en-US) 255 (fr-FR) 255 (de-DE) 255 (es-ES) - // - } + Console.WriteLine(); + } + // The example displays the following output to the console: + // 0 (en-US) 0 (fr-FR) 0 (de-DE) 0 (es-ES) + // 1 (en-US) 1 (fr-FR) 1 (de-DE) 1 (es-ES) + // 14 (en-US) 14 (fr-FR) 14 (de-DE) 14 (es-ES) + // 168 (en-US) 168 (fr-FR) 168 (de-DE) 168 (es-ES) + // 255 (en-US) 255 (fr-FR) 255 (de-DE) 255 (es-ES) + // + } - private static void SpecifyFormatString() - { - // - string[] formats = {"C3", "D4", "e1", "E2", "F1", "G", "N1", + private static void SpecifyFormatString() + { + // + string[] formats = {"C3", "D4", "e1", "E2", "F1", "G", "N1", "P0", "X4", "0000.0000"}; - byte number = 240; - foreach (string format in formats) - Console.WriteLine("'{0}' format specifier: {1}", - format, number.ToString(format)); + byte number = 240; + foreach (string format in formats) + Console.WriteLine($"'{format}' format specifier: {number.ToString(format)}"); - // The example displays the following output to the console if the - // current culture is en-us: - // 'C3' format specifier: $240.000 - // 'D4' format specifier: 0240 - // 'e1' format specifier: 2.4e+002 - // 'E2' format specifier: 2.40E+002 - // 'F1' format specifier: 240.0 - // 'G' format specifier: 240 - // 'N1' format specifier: 240.0 - // 'P0' format specifier: 24,000 % - // 'X4' format specifier: 00F0 - // '0000.0000' format specifier: 0240.0000 - // - } + // The example displays the following output to the console if the + // current culture is en-us: + // 'C3' format specifier: $240.000 + // 'D4' format specifier: 0240 + // 'e1' format specifier: 2.4e+002 + // 'E2' format specifier: 2.40E+002 + // 'F1' format specifier: 240.0 + // 'G' format specifier: 240 + // 'N1' format specifier: 240.0 + // 'P0' format specifier: 24,000 % + // 'X4' format specifier: 00F0 + // '0000.0000' format specifier: 0240.0000 + // + } - private static void FormatWithProviders() - { - // - byte byteValue = 250; - CultureInfo[] providers = {new CultureInfo("en-us"), + private static void FormatWithProviders() + { + // + byte byteValue = 250; + CultureInfo[] providers = {new CultureInfo("en-us"), new CultureInfo("fr-fr"), new CultureInfo("es-es"), new CultureInfo("de-de")}; - foreach (CultureInfo provider in providers) - Console.WriteLine("{0} ({1})", - byteValue.ToString("N2", provider), provider.Name); - // The example displays the following output to the console: - // 250.00 (en-US) - // 250,00 (fr-FR) - // 250,00 (es-ES) - // 250,00 (de-DE) - // - } + foreach (CultureInfo provider in providers) + Console.WriteLine($"{byteValue.ToString("N2", provider)} ({provider.Name})"); + // The example displays the following output to the console: + // 250.00 (en-US) + // 250,00 (fr-FR) + // 250,00 (es-ES) + // 250,00 (de-DE) + // + } } diff --git a/snippets/csharp/System/Byte/ToString/tostring.cs b/snippets/csharp/System/Byte/ToString/tostring.cs index 0bd10a41446..a9e6039a9c5 100644 --- a/snippets/csharp/System/Byte/ToString/tostring.cs +++ b/snippets/csharp/System/Byte/ToString/tostring.cs @@ -5,28 +5,24 @@ class ByteToStringDemo { - static void RunToStringDemo( ) + static void RunToStringDemo() { byte smallValue = 13; byte largeValue = 234; // Format the Byte values without and with format strings. - Console.WriteLine( "\nIFormatProvider is not used:" ); - Console.WriteLine( " {0,-20}{1,10}{2,10}", - "No format string:", smallValue.ToString( ), - largeValue.ToString( ) ); - Console.WriteLine( " {0,-20}{1,10}{2,10}", - "'X2' format string:", smallValue.ToString( "X2" ), - largeValue.ToString( "X2" ) ); + Console.WriteLine("\nIFormatProvider is not used:"); + Console.WriteLine($" {"No format string:",-20}{smallValue.ToString(),10}{largeValue.ToString(),10}"); + Console.WriteLine($" {"'X2' format string:",-20}{smallValue.ToString("X2"),10}{largeValue.ToString("X2"),10}"); // Get the NumberFormatInfo object from the // invariant culture. - CultureInfo culture = new CultureInfo( "" ); - NumberFormatInfo numInfo = culture.NumberFormat; + CultureInfo culture = new(""); + NumberFormatInfo numInfo = culture.NumberFormat; // Set the digit grouping to 1, set the digit separator // to underscore, and set decimal digits to 0. - numInfo.NumberGroupSizes = new int[ ] { 1 }; + numInfo.NumberGroupSizes = new int[] { 1 }; numInfo.NumberGroupSeparator = "_"; numInfo.NumberDecimalDigits = 0; @@ -34,28 +30,23 @@ static void RunToStringDemo( ) Console.WriteLine( "\nA NumberFormatInfo object with digit group " + "size = 1 and \ndigit separator " + - "= '_' is used for the IFormatProvider:" ); - Console.WriteLine( " {0,-20}{1,10}{2,10}", - "No format string:", smallValue.ToString( numInfo ), - largeValue.ToString( numInfo ) ); - Console.WriteLine( " {0,-20}{1,10}{2,10}", - "'N' format string:", - smallValue.ToString( "N", numInfo ), - largeValue.ToString( "N", numInfo ) ); + "= '_' is used for the IFormatProvider:"); + Console.WriteLine($" {"No format string:",-20}{smallValue.ToString(numInfo),10}{largeValue.ToString(numInfo),10}"); + Console.WriteLine($" {"'N' format string:",-20}{smallValue.ToString("N", numInfo),10}{largeValue.ToString("N", numInfo),10}"); } - static void Main( ) + static void Main() { - Console.WriteLine( "This example of\n" + + Console.WriteLine("This example of\n" + " Byte.ToString( ),\n" + " Byte.ToString( String ),\n" + " Byte.ToString( IFormatProvider ), and\n" + " Byte.ToString( String, IFormatProvider )\n" + "generates the following output when formatting " + "Byte values \nwith combinations of format " + - "strings and IFormatProvider." ); + "strings and IFormatProvider."); - RunToStringDemo( ); + RunToStringDemo(); } } diff --git a/snippets/csharp/System/Byte/TryParse/TryParse.cs b/snippets/csharp/System/Byte/TryParse/TryParse.cs index 130b244d68d..0b096edcb7e 100644 --- a/snippets/csharp/System/Byte/TryParse/TryParse.cs +++ b/snippets/csharp/System/Byte/TryParse/TryParse.cs @@ -3,34 +3,32 @@ public class ByteConversion { - public static void Main() - { - string[] byteStrings = { null, string.Empty, "1024", + public static void Main() + { + string[] byteStrings = { null, string.Empty, "1024", "100.1", "100", "+100", "-100", "000000000000000100", "00,100", " 20 ", "FF", "0x1F" }; - foreach (var byteString in byteStrings) - { - CallTryParse(byteString); - } - } + foreach (string byteString in byteStrings) + { + CallTryParse(byteString); + } + } - private static void CallTryParse(string stringToConvert) - { - byte byteValue; - bool success = Byte.TryParse(stringToConvert, out byteValue); - if (success) - { - Console.WriteLine("Converted '{0}' to {1}", - stringToConvert, byteValue); - } - else - { - Console.WriteLine("Attempted conversion of '{0}' failed.", - stringToConvert); - } - } + private static void CallTryParse(string stringToConvert) + { + byte byteValue; + bool success = byte.TryParse(stringToConvert, out byteValue); + if (success) + { + Console.WriteLine($"Converted '{stringToConvert}' to {byteValue}"); + } + else + { + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } + } } // The example displays the following output to the console: // Attempted conversion of '' failed. diff --git a/snippets/csharp/System/Byte/TryParse/TryParse2.cs b/snippets/csharp/System/Byte/TryParse/TryParse2.cs index 73660c72d69..e8d9a19e5fe 100644 --- a/snippets/csharp/System/Byte/TryParse/TryParse2.cs +++ b/snippets/csharp/System/Byte/TryParse/TryParse2.cs @@ -4,61 +4,59 @@ public class ByteConversion2 { - public static void Main() - { - string byteString; - NumberStyles styles; + public static void Main() + { + string byteString; + NumberStyles styles; - byteString = "1024"; - styles = NumberStyles.Integer; - CallTryParse(byteString, styles); + byteString = "1024"; + styles = NumberStyles.Integer; + CallTryParse(byteString, styles); - byteString = "100.1"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(byteString, styles); + byteString = "100.1"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(byteString, styles); - byteString = "100.0"; - CallTryParse(byteString, styles); + byteString = "100.0"; + CallTryParse(byteString, styles); - byteString = "+100"; - styles = NumberStyles.Integer | NumberStyles.AllowLeadingSign - | NumberStyles.AllowTrailingSign; - CallTryParse(byteString, styles); + byteString = "+100"; + styles = NumberStyles.Integer | NumberStyles.AllowLeadingSign + | NumberStyles.AllowTrailingSign; + CallTryParse(byteString, styles); - byteString = "-100"; - CallTryParse(byteString, styles); + byteString = "-100"; + CallTryParse(byteString, styles); - byteString = "000000000000000100"; - CallTryParse(byteString, styles); + byteString = "000000000000000100"; + CallTryParse(byteString, styles); - byteString = "00,100"; - styles = NumberStyles.Integer | NumberStyles.AllowThousands; - CallTryParse(byteString, styles); + byteString = "00,100"; + styles = NumberStyles.Integer | NumberStyles.AllowThousands; + CallTryParse(byteString, styles); - byteString = "2E+3 "; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(byteString, styles); + byteString = "2E+3 "; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(byteString, styles); - byteString = "FF"; - styles = NumberStyles.HexNumber; - CallTryParse(byteString, styles); + byteString = "FF"; + styles = NumberStyles.HexNumber; + CallTryParse(byteString, styles); - byteString = "0x1F"; - CallTryParse(byteString, styles); - } + byteString = "0x1F"; + CallTryParse(byteString, styles); + } - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - Byte byteValue; - bool result = Byte.TryParse(stringToConvert, styles, - null as IFormatProvider, out byteValue); - if (result) - Console.WriteLine("Converted '{0}' to {1}", - stringToConvert, byteValue); - else - Console.WriteLine("Attempted conversion of '{0}' failed.", - stringToConvert.ToString()); - } + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + byte byteValue; + bool result = byte.TryParse(stringToConvert, styles, + null as IFormatProvider, out byteValue); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {byteValue}"); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert.ToString()}' failed."); + } } // The example displays the following output to the console: // Attempted conversion of '1024' failed.