diff --git a/snippets/csharp/System/UInt16/CompareTo/source.cs b/snippets/csharp/System/UInt16/CompareTo/source.cs index d5e48a9c9b7..18aa0072d82 100644 --- a/snippets/csharp/System/UInt16/CompareTo/source.cs +++ b/snippets/csharp/System/UInt16/CompareTo/source.cs @@ -1,314 +1,314 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("G", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - - Console.ReadLine(); - } - } - // - /// - /// Temperature class stores the value as UInt16 - /// and delegates most of the functionality - /// to the UInt16 implementation. - /// - public class Temperature : IComparable, IFormattable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt16.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets +{ + class Launcher + { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("G", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + + Console.ReadLine(); + } + } + // + /// + /// Temperature class stores the value as UInt16 + /// and delegates most of the functionality + /// to the UInt16 implementation. + /// + public class Temperature : IComparable, IFormattable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ushort.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static ushort MinValue { - get { - return UInt16.MinValue; - } - } - - public static ushort MaxValue { - get { - return UInt16.MaxValue; - } - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static ushort MinValue => ushort.MinValue; + + public static ushort MaxValue => ushort.MaxValue; + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets3 +{ + // + public class Temperature : IComparable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = UInt16.Parse(s); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = ushort.Parse(s); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = UInt16.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = ushort.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = UInt16.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = ushort.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt16.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ushort.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } diff --git a/snippets/csharp/System/UInt16/Equals/equalsoverl.cs b/snippets/csharp/System/UInt16/Equals/equalsoverl.cs index b14ee0a95c1..6cb59e8a592 100644 --- a/snippets/csharp/System/UInt16/Equals/equalsoverl.cs +++ b/snippets/csharp/System/UInt16/Equals/equalsoverl.cs @@ -3,42 +3,36 @@ public class Example { - static ushort value = 112; - - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); - - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); - - int int1 = 112; - Console.WriteLine("value = int1: {0,19}", value.Equals(int1)); - TestObjectForEquality(int1); - - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); - - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); - - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } - - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + static ushort value = 112; + + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); + + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); + + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),19}"); + TestObjectForEquality(int1); + + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); + + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); + + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } + + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/UInt16/Equals/uint16_equals.cs b/snippets/csharp/System/UInt16/Equals/uint16_equals.cs index 491153d04f5..7fc6e0c14b2 100644 --- a/snippets/csharp/System/UInt16/Equals/uint16_equals.cs +++ b/snippets/csharp/System/UInt16/Equals/uint16_equals.cs @@ -15,8 +15,8 @@ public static void MyMethod() try { // - UInt16 myVariable1 = 10; - UInt16 myVariable2 = 10; + ushort myVariable1 = 10; + ushort myVariable2 = 10; //Display the declaring type. Console.WriteLine("\nType of 'myVariable1' is '{0}' and" + @@ -36,7 +36,7 @@ public static void MyMethod() } catch (Exception e) { - Console.WriteLine("Exception :{0}", e.Message); + Console.WriteLine($"Exception :{e.Message}"); } } } diff --git a/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs b/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs index 2a8b2056e75..07f7049d003 100644 --- a/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs +++ b/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs @@ -2,21 +2,21 @@ public class Class1 { - public static void Main() - { - // - int integerValue = 1216; - ushort uIntegerValue; - - if (integerValue >= ushort.MinValue & integerValue <= ushort.MaxValue) - { - uIntegerValue = (ushort) integerValue; - Console.WriteLine(uIntegerValue); - } - else - { - Console.WriteLine("Unable to convert {0} to a UInt16t.", integerValue); - } - // - } + public static void Main() + { + // + int integerValue = 1216; + ushort uIntegerValue; + + if (integerValue >= ushort.MinValue && integerValue <= ushort.MaxValue) + { + uIntegerValue = (ushort)integerValue; + Console.WriteLine(uIntegerValue); + } + else + { + Console.WriteLine($"Unable to convert {integerValue} to a UInt16."); + } + // + } } diff --git a/snippets/csharp/System/UInt16/Parse/Program.cs b/snippets/csharp/System/UInt16/Parse/Program.cs new file mode 100644 index 00000000000..48b8ef24291 --- /dev/null +++ b/snippets/csharp/System/UInt16/Parse/Program.cs @@ -0,0 +1,4 @@ +UInt16ParseExample2.Run(); +UInt16ParseExample3.Run(); +UInt16ParseExample4.Run(); +UInt16ParseExample5.Run(); diff --git a/snippets/csharp/System/UInt16/Parse/Project.csproj b/snippets/csharp/System/UInt16/Parse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt16/Parse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt16/Parse/parseex2.cs b/snippets/csharp/System/UInt16/Parse/parseex2.cs index 8f62ab5df7c..1b570b10a8a 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex2.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex2.cs @@ -2,34 +2,36 @@ using System; using System.Globalization; -public class Example +public class UInt16ParseExample2 { - public static void Main() - { - string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }; - NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; - NumberStyles[] styles = { NumberStyles.None, whitespace, - NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, - NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, + public static void Run() + { + string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }; + NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; + NumberStyles[] styles = { NumberStyles.None, whitespace, + NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, + NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint }; - // Attempt to convert each number using each style combination. - foreach (string value in values) - { - Console.WriteLine("Attempting to convert '{0}':", value); - foreach (NumberStyles style in styles) - { - try { - ushort number = UInt16.Parse(value, style); - Console.WriteLine(" {0}: {1}", style, number); - } - catch (FormatException) { - Console.WriteLine(" {0}: Bad Format", style); + // Attempt to convert each number using each style combination. + foreach (string value in values) + { + Console.WriteLine($"Attempting to convert '{value}':"); + foreach (NumberStyles style in styles) + { + try + { + ushort number = ushort.Parse(value, style); + Console.WriteLine($" {style}: {number}"); + } + catch (FormatException) + { + Console.WriteLine($" {style}: Bad Format"); + } } - } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example display the following output: // Attempting to convert ' 214 ': @@ -38,56 +40,56 @@ public static void Main() // Integer, AllowTrailingSign: 214 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1,064': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: 1064 // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '(0)': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1241+': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 1241 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' + 214 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' +214 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 214 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '2153.0': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 2153 -// +// // Attempting to convert '1e03': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 1000 -// +// // Attempting to convert '1300.0e-2': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format diff --git a/snippets/csharp/System/UInt16/Parse/parseex3.cs b/snippets/csharp/System/UInt16/Parse/parseex3.cs index ec51129ab1d..0e3f0e06292 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex3.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex3.cs @@ -2,37 +2,40 @@ using System; using System.Globalization; -public class Example +public class UInt16ParseExample3 { - public static void Main() - { - // Define a custom culture that uses "++" as a positive sign. - CultureInfo ci = new CultureInfo(""); - ci.NumberFormat.PositiveSign = "++"; - // Create an array of cultures. - CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture }; - // Create an array of strings to parse. - string[] values = { "++1403", "-0", "+0", "+16034", - Int16.MinValue.ToString(), "14.0", "18012" }; - // Parse the strings using each culture. - foreach (CultureInfo culture in cultures) - { - Console.WriteLine("Parsing with the '{0}' culture.", culture.Name); - foreach (string value in values) - { - try { - ushort number = UInt16.Parse(value, culture); - Console.WriteLine(" Converted '{0}' to {1}.", value, number); + public static void Run() + { + // Define a custom culture that uses "++" as a positive sign. + CultureInfo ci = new(""); + ci.NumberFormat.PositiveSign = "++"; + // Create an array of cultures. + CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture }; + // Create an array of strings to parse. + string[] values = { "++1403", "-0", "+0", "+16034", + short.MinValue.ToString(), "14.0", "18012" }; + // Parse the strings using each culture. + foreach (CultureInfo culture in cultures) + { + Console.WriteLine($"Parsing with the '{culture.Name}' culture."); + foreach (string value in values) + { + try + { + ushort number = ushort.Parse(value, culture); + Console.WriteLine($" Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($" The format of '{value}' is invalid."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is outside the range of a UInt16 value."); + } } - catch (FormatException) { - Console.WriteLine(" The format of '{0}' is invalid.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value); - } - } - } - } + } + } } // The example displays the following output: // Parsing with the culture. diff --git a/snippets/csharp/System/UInt16/Parse/parseex4.cs b/snippets/csharp/System/UInt16/Parse/parseex4.cs index 84d41b378da..1ef871ac156 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex4.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex4.cs @@ -2,44 +2,44 @@ using System; using System.Globalization; -public class Example +public class UInt16ParseExample4 { - public static void Main() - { - string[] cultureNames = { "en-US", "fr-FR" }; - NumberStyles[] styles= { NumberStyles.Integer, + public static void Run() + { + string[] cultureNames = { "en-US", "fr-FR" }; + NumberStyles[] styles = { NumberStyles.Integer, NumberStyles.Integer | NumberStyles.AllowDecimalPoint }; - string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00", + string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00", "-1032,00", "1045.1", "1045,1" }; - - // Parse strings using each culture - foreach (string cultureName in cultureNames) - { - CultureInfo ci = new CultureInfo(cultureName); - Console.WriteLine("Parsing strings using the {0} culture", - ci.DisplayName); - // Use each style. - foreach (NumberStyles style in styles) - { - Console.WriteLine(" Style: {0}", style.ToString()); - // Parse each numeric string. - foreach (string value in values) + + // Parse strings using each culture + foreach (string cultureName in cultureNames) + { + CultureInfo ci = new(cultureName); + Console.WriteLine($"Parsing strings using the {ci.DisplayName} culture"); + // Use each style. + foreach (NumberStyles style in styles) { - try { - Console.WriteLine(" Converted '{0}' to {1}.", value, - UInt16.Parse(value, style, ci)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the UInt16 type.", - value); - } + Console.WriteLine($" Style: {style.ToString()}"); + // Parse each numeric string. + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {ushort.Parse(value, style, ci)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the UInt16 type."); + } + } } - } - } - } + } + } } // The example displays the following output: // Parsing strings using the English (United States) culture diff --git a/snippets/csharp/System/UInt16/Parse/parseex5.cs b/snippets/csharp/System/UInt16/Parse/parseex5.cs index aff233c5bbf..889f620b5cb 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex5.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex5.cs @@ -1,29 +1,33 @@ // using System; -public class Example +public class UInt16ParseExample5 { - public static void Main() - { - string[] values = { "-0", "17", "-12", "185", "66012", "+0", + public static void Run() + { + string[] values = { "-0", "17", "-12", "185", "66012", "+0", "", null, "16.1", "28.0", "1,034" }; - foreach (string value in values) - { - try { - ushort number = UInt16.Parse(value); - Console.WriteLine("'{0}' --> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("'{0}' --> Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("'{0}' --> OverflowException", value); - } - catch (ArgumentNullException) { - Console.WriteLine("'{0}' --> Null", value); - } - } - } + foreach (string value in values) + { + try + { + ushort number = ushort.Parse(value); + Console.WriteLine($"'{value}' --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"'{value}' --> Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"'{value}' --> OverflowException"); + } + catch (ArgumentNullException) + { + Console.WriteLine($"'{value}' --> Null"); + } + } + } } // The example displays the following output: // '-0' --> 0 diff --git a/snippets/csharp/System/UInt16/ToString/Program.cs b/snippets/csharp/System/UInt16/ToString/Program.cs new file mode 100644 index 00000000000..860773be472 --- /dev/null +++ b/snippets/csharp/System/UInt16/ToString/Program.cs @@ -0,0 +1,4 @@ +UInt16ToStringExample1.Run(); +UInt16ToStringExample2.Run(); +UInt16ToStringExample3.Run(); +UInt16ToStringExample4.Run(); diff --git a/snippets/csharp/System/UInt16/ToString/Project.csproj b/snippets/csharp/System/UInt16/ToString/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt16/ToString/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt16/ToString/tostring1.cs b/snippets/csharp/System/UInt16/ToString/tostring1.cs index e81bfddcffc..6acfb024b97 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring1.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring1.cs @@ -1,22 +1,21 @@ // using System; -public class Example +public class UInt16ToStringExample1 { - public static void Main() - { - ushort value = 16324; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); - Console.WriteLine(); - - // Define an array of format specifiers. - string[] formats = { "G", "C", "D", "F", "N", "X" }; - // Display value using the standard format specifiers. - foreach (string format in formats) - Console.WriteLine("{0} format specifier: {1,12}", - format, value.ToString(format)); - } + public static void Run() + { + ushort value = 16324; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); + Console.WriteLine(); + + // Define an array of format specifiers. + string[] formats = { "G", "C", "D", "F", "N", "X" }; + // Display value using the standard format specifiers. + foreach (string format in formats) + Console.WriteLine($"{format} format specifier: {value.ToString(format),12}"); + } } // The example displays the following output: // 16324 diff --git a/snippets/csharp/System/UInt16/ToString/tostring2.cs b/snippets/csharp/System/UInt16/ToString/tostring2.cs index 1075f803ea9..6324bf04a36 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring2.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring2.cs @@ -2,28 +2,26 @@ using System; using System.Globalization; -public class Example +public class UInt16ToStringExample2 { - public static void Main() - { - // Define an array of CultureInfo objects. - CultureInfo[] ci = { new CultureInfo("en-US"), - new CultureInfo("fr-FR"), - CultureInfo.InvariantCulture }; - UInt16 value = 18924; - Console.WriteLine(" {0,12} {1,12} {2,12}", - GetName(ci[0]), GetName(ci[1]), GetName(ci[2])); - Console.WriteLine(" {0,12} {1,12} {2,12}", - value.ToString(ci[0]), value.ToString(ci[1]), value.ToString(ci[2])); - } + public static void Run() + { + // Define an array of CultureInfo objects. + CultureInfo[] ci = { new CultureInfo("en-US"), + new CultureInfo("fr-FR"), + CultureInfo.InvariantCulture }; + ushort value = 18924; + Console.WriteLine($" {GetName(ci[0]),12} {GetName(ci[1]),12} {GetName(ci[2]),12}"); + Console.WriteLine($" {value.ToString(ci[0]),12} {value.ToString(ci[1]),12} {value.ToString(ci[2]),12}"); + } - private static string GetName(CultureInfo ci) - { - if (ci.Equals(CultureInfo.InvariantCulture)) - return "Invariant"; - else - return ci.Name; - } + private static string GetName(CultureInfo ci) + { + if (ci.Equals(CultureInfo.InvariantCulture)) + return "Invariant"; + else + return ci.Name; + } } // The example displays the following output: // en-US fr-FR Invariant diff --git a/snippets/csharp/System/UInt16/ToString/tostring3.cs b/snippets/csharp/System/UInt16/ToString/tostring3.cs index a8793f054b2..236354a6c8c 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring3.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring3.cs @@ -1,19 +1,19 @@ // using System; -using System.Globalization; -public class Example + +public class UInt16ToStringExample3 { - public static void Main() - { - ushort value = 21708; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "000000.0", "#.0", + public static void Run() + { + ushort value = 21708; + string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "000000.0", "#.0", "00000000;(0);**Zero**" }; - - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - } + + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + } } // The example displays the following output: // G: 21708 diff --git a/snippets/csharp/System/UInt16/ToString/tostring4.cs b/snippets/csharp/System/UInt16/ToString/tostring4.cs index 8df6ae52e67..4c3a57d7e2a 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring4.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring4.cs @@ -2,56 +2,54 @@ using System; using System.Globalization; -public class Example +public class UInt16ToStringExample4 { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), - CultureInfo.CreateSpecificCulture("fr-FR"), + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), + CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("es-ES") }; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - ushort value = 22042; - - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 16}", - specifier, culture.Name, - value.ToString(specifier, culture)); - Console.WriteLine(); - } - } + string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" }; + ushort value = 22042; + + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {value.ToString(specifier, culture),16}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 22042 // G format using fr-FR culture: 22042 // G format using es-ES culture: 22042 -// +// // C format using en-US culture: $22,042.00 // C format using fr-FR culture: 22 042,00 € // C format using es-ES culture: 22.042,00 € -// +// // D4 format using en-US culture: 22042 // D4 format using fr-FR culture: 22042 // D4 format using es-ES culture: 22042 -// +// // E2 format using en-US culture: 2.20E+004 // E2 format using fr-FR culture: 2,20E+004 // E2 format using es-ES culture: 2,20E+004 -// +// // F format using en-US culture: 22042.00 // F format using fr-FR culture: 22042,00 // F format using es-ES culture: 22042,00 -// +// // N format using en-US culture: 22,042.00 // N format using fr-FR culture: 22 042,00 // N format using es-ES culture: 22.042,00 -// +// // P format using en-US culture: 2,204,200.00 % // P format using fr-FR culture: 2 204 200,00 % // P format using es-ES culture: 2.204.200,00 % -// +// // X2 format using en-US culture: 561A // X2 format using fr-FR culture: 561A // X2 format using es-ES culture: 561A diff --git a/snippets/csharp/System/UInt16/TryParse/Program.cs b/snippets/csharp/System/UInt16/TryParse/Program.cs new file mode 100644 index 00000000000..1958e43db86 --- /dev/null +++ b/snippets/csharp/System/UInt16/TryParse/Program.cs @@ -0,0 +1,3 @@ +UInt16TryParseStylesExample.Run(); +UInt32TryParseBasicExample.Run(); +UInt32TryParseStylesExample.Run(); diff --git a/snippets/csharp/System/UInt16/TryParse/Project.csproj b/snippets/csharp/System/UInt16/TryParse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt16/TryParse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt16/TryParse/tryparse11.cs b/snippets/csharp/System/UInt16/TryParse/tryparse11.cs index 24a2fa998b5..c068b5d4c35 100644 --- a/snippets/csharp/System/UInt16/TryParse/tryparse11.cs +++ b/snippets/csharp/System/UInt16/TryParse/tryparse11.cs @@ -1,36 +1,36 @@ using System; -public class Example +public class UInt32TryParseBasicExample { - public static void Main() - { - // - string[] numericStrings = { "1293.8", "+1671.7", "28347.", - " 33113684 ", "(0)", "-0", "-1", - "+1293617", "18-", "119870", "31,024", + public static void Run() + { + // + string[] numericStrings = { "1293.8", "+1671.7", "28347.", + " 33113684 ", "(0)", "-0", "-1", + "+1293617", "18-", "119870", "31,024", " 3127094 ", "00700000" }; - uint number; - foreach (string numericString in numericStrings) - { - if (UInt32.TryParse(numericString, out number)) - Console.WriteLine("Converted '{0}' to {1}.", numericString, number); - else - Console.WriteLine("Cannot convert '{0}' to a UInt32.", numericString); - } - // The example displays the following output: - // Cannot convert '1293.8' to a UInt32. - // Cannot convert '+1671.7' to a UInt32. - // Cannot convert '28347.' to a UInt32. - // Converted ' 33113684 ' to 33113684. - // Cannot convert '(0)' to a UInt32. - // Converted '-0' to 0. - // Cannot convert '-1' to a UInt32. - // Converted '+1293617' to 1293617. - // Cannot convert '18-' to a UInt32. - // Converted '119870' to 119870. - // Cannot convert '31,024' to a UInt32. - // Converted ' 3127094 ' to 3127094. - // Converted '0070000' to 70000. - // - } + uint number; + foreach (string numericString in numericStrings) + { + if (uint.TryParse(numericString, out number)) + Console.WriteLine($"Converted '{numericString}' to {number}."); + else + Console.WriteLine($"Cannot convert '{numericString}' to a UInt32."); + } + // The example displays the following output: + // Cannot convert '1293.8' to a UInt32. + // Cannot convert '+1671.7' to a UInt32. + // Cannot convert '28347.' to a UInt32. + // Converted ' 33113684 ' to 33113684. + // Cannot convert '(0)' to a UInt32. + // Converted '-0' to 0. + // Cannot convert '-1' to a UInt32. + // Converted '+1293617' to 1293617. + // Cannot convert '18-' to a UInt32. + // Converted '119870' to 119870. + // Cannot convert '31,024' to a UInt32. + // Converted ' 3127094 ' to 3127094. + // Converted '0070000' to 70000. + // + } } diff --git a/snippets/csharp/System/UInt16/TryParse/tryparse2.cs b/snippets/csharp/System/UInt16/TryParse/tryparse2.cs index d97093927b3..226fa126d16 100644 --- a/snippets/csharp/System/UInt16/TryParse/tryparse2.cs +++ b/snippets/csharp/System/UInt16/TryParse/tryparse2.cs @@ -2,56 +2,56 @@ using System; using System.Globalization; -public class Example +public class UInt16TryParseStylesExample { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "10603"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-10603"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "29103.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "10345.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Run() + { + string numericString; + NumberStyles styles; - numericString = "2210E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "9112E-01"; - CallTryParse(numericString, styles); - - numericString = "312E01"; - CallTryParse(numericString, styles); - - numericString = "FFC8"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8F8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - ushort number; - bool result = UInt16.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "10603"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-10603"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "29103.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10345.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "2210E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "9112E-01"; + CallTryParse(numericString, styles); + + numericString = "312E01"; + CallTryParse(numericString, styles); + + numericString = "FFC8"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8F8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + ushort number; + bool result = ushort.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '10603' to 10603. diff --git a/snippets/csharp/System/UInt16/TryParse/tryparse21.cs b/snippets/csharp/System/UInt16/TryParse/tryparse21.cs index 8c55b83e78e..dec240c9d9c 100644 --- a/snippets/csharp/System/UInt16/TryParse/tryparse21.cs +++ b/snippets/csharp/System/UInt16/TryParse/tryparse21.cs @@ -2,56 +2,56 @@ using System; using System.Globalization; -public class Example +public class UInt32TryParseStylesExample { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "2106034"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-10603"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "29103674.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "10345.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Run() + { + string numericString; + NumberStyles styles; - numericString = "41792210E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "9112E-01"; - CallTryParse(numericString, styles); - - numericString = "312E01"; - CallTryParse(numericString, styles); - - numericString = "FFC86DA1"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8F8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - uint number; - bool result = UInt32.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "2106034"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-10603"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "29103674.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10345.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "41792210E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "9112E-01"; + CallTryParse(numericString, styles); + + numericString = "312E01"; + CallTryParse(numericString, styles); + + numericString = "FFC86DA1"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8F8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + uint number; + bool result = uint.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '2106034' to 2106034. diff --git a/snippets/csharp/System/UInt32/CompareTo/source.cs b/snippets/csharp/System/UInt32/CompareTo/source.cs index 31f0f2ce977..e2496483bef 100644 --- a/snippets/csharp/System/UInt32/CompareTo/source.cs +++ b/snippets/csharp/System/UInt32/CompareTo/source.cs @@ -1,314 +1,314 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("G", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - - Console.ReadLine(); - } - } - // - /// - /// Temperature class stores the value as UInt32 - /// and delegates most of the functionality - /// to the UInt32 implementation. - /// - public class Temperature : IComparable, IFormattable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt32.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets +{ + class Launcher + { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("G", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + + Console.ReadLine(); + } + } + // + /// + /// Temperature class stores the value as UInt32 + /// and delegates most of the functionality + /// to the UInt32 implementation. + /// + public class Temperature : IComparable, IFormattable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = uint.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static uint MinValue { - get { - return UInt32.MinValue; - } - } - - public static uint MaxValue { - get { - return UInt32.MaxValue; - } - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static uint MinValue => uint.MinValue; + + public static uint MaxValue => uint.MaxValue; + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets3 +{ + // + public class Temperature : IComparable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = UInt32.Parse(s); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = uint.Parse(s); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = UInt32.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = uint.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = UInt32.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = uint.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt32.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = uint.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } diff --git a/snippets/csharp/System/UInt32/Equals/equalsoverl.cs b/snippets/csharp/System/UInt32/Equals/equalsoverl.cs index 53f0ee58e22..186405bfe27 100644 --- a/snippets/csharp/System/UInt32/Equals/equalsoverl.cs +++ b/snippets/csharp/System/UInt32/Equals/equalsoverl.cs @@ -3,50 +3,44 @@ public class Example { - static uint value = 112; - - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); + static uint value = 112; - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); - long long1 = 112; - Console.WriteLine("value = long1: {0,18}", value.Equals(long1)); - TestObjectForEquality(long1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + long long1 = 112; + Console.WriteLine($"value = long1: {value.Equals(long1),18}"); + TestObjectForEquality(long1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); - ulong ulong1 = 112; - Console.WriteLine("value = ulong1: {0,18}", value.Equals(ulong1)); - TestObjectForEquality(ulong1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}"); + TestObjectForEquality(ushort1); - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); + ulong ulong1 = 112; + Console.WriteLine($"value = ulong1: {value.Equals(ulong1),18}"); + TestObjectForEquality(ulong1); - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } + + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/UInt32/Equals/uint32_equals.cs b/snippets/csharp/System/UInt32/Equals/uint32_equals.cs index f5966b5ac63..6fe36d5cf47 100644 --- a/snippets/csharp/System/UInt32/Equals/uint32_equals.cs +++ b/snippets/csharp/System/UInt32/Equals/uint32_equals.cs @@ -9,32 +9,32 @@ of struct 'UInt32'. This compares an instance of 'UInt32' with the using System; class MyUInt32_Equals { - public static void Main() - { - try - { -// - UInt32 myVariable1 = 20; - UInt32 myVariable2 = 20; + public static void Main() + { + try + { + // + uint myVariable1 = 20; + uint myVariable2 = 20; // Display the declaring type. - Console.WriteLine("\nType of 'myVariable1' is '{0}' and"+ - " value is :{1}",myVariable1.GetType(), myVariable1); - Console.WriteLine("Type of 'myVariable2' is '{0}' and"+ - " value is :{1}",myVariable2.GetType(), myVariable2); + Console.WriteLine("\nType of 'myVariable1' is '{0}' and" + + " value is :{1}", myVariable1.GetType(), myVariable1); + Console.WriteLine("Type of 'myVariable2' is '{0}' and" + + " value is :{1}", myVariable2.GetType(), myVariable2); // Compare 'myVariable1' instance with 'myVariable2' Object. - if( myVariable1.Equals( myVariable2 ) ) - Console.WriteLine( "\nStructures 'myVariable1' and "+ - "'myVariable2' are equal"); + if (myVariable1.Equals(myVariable2)) + Console.WriteLine("\nStructures 'myVariable1' and " + + "'myVariable2' are equal"); else - Console.WriteLine( "\nStructures 'myVariable1' and "+ - "'myVariable2' are not equal"); -// - } - catch(Exception e) - { - Console.WriteLine("Exception :{0}", e.Message); - } - } + Console.WriteLine("\nStructures 'myVariable1' and " + + "'myVariable2' are not equal"); + // + } + catch (Exception e) + { + Console.WriteLine($"Exception :{e.Message}"); + } + } } diff --git a/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs b/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs index e468978f860..74a2b056a11 100644 --- a/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs +++ b/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs @@ -2,40 +2,36 @@ public class ULongRangeExample { - public static void Main() - { - // - long longValue = long.MaxValue / 2; - uint integerValue; - - if (longValue <= uint.MaxValue && - longValue >= uint.MinValue) - { - integerValue = (uint) longValue; - Console.WriteLine("Converted long integer value to {0:n0}.", - integerValue); - } - else - { - uint rangeLimit; - string relationship; - - if (longValue > uint.MaxValue) - { - rangeLimit = uint.MaxValue; - relationship = "greater"; - } - else - { - rangeLimit = uint.MinValue; - relationship = "less"; - } + public static void Main() + { + // + long longValue = long.MaxValue / 2; + uint integerValue; - Console.WriteLine("Conversion failure: {0:n0} is {1} than {2:n0}", - longValue, - relationship, - rangeLimit); - } - // - } + if (longValue <= uint.MaxValue && + longValue >= uint.MinValue) + { + integerValue = (uint)longValue; + Console.WriteLine($"Converted long integer value to {integerValue:n0}."); + } + else + { + uint rangeLimit; + string relationship; + + if (longValue > uint.MaxValue) + { + rangeLimit = uint.MaxValue; + relationship = "greater"; + } + else + { + rangeLimit = uint.MinValue; + relationship = "less"; + } + + Console.WriteLine($"Conversion failure: {longValue:n0} is {relationship} than {rangeLimit:n0}"); + } + // + } } diff --git a/snippets/csharp/System/UInt32/Parse/Program.cs b/snippets/csharp/System/UInt32/Parse/Program.cs new file mode 100644 index 00000000000..457da988a89 --- /dev/null +++ b/snippets/csharp/System/UInt32/Parse/Program.cs @@ -0,0 +1,3 @@ +ParseExample1.Run(); +ParseExample2.Run(); +ParseExample4.Run(); diff --git a/snippets/csharp/System/UInt32/Parse/Project.csproj b/snippets/csharp/System/UInt32/Parse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt32/Parse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt32/Parse/parse1.cs b/snippets/csharp/System/UInt32/Parse/parse1.cs index ec04e314312..faa339fdbac 100644 --- a/snippets/csharp/System/UInt32/Parse/parse1.cs +++ b/snippets/csharp/System/UInt32/Parse/parse1.cs @@ -1,39 +1,42 @@ using System; -public class Example +public class ParseExample1 { - public static void Main() - { - // - string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", - "0xFA1B", "163042", "-10", "2147483648", + public static void Run() + { + // + string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", + "0xFA1B", "163042", "-10", "2147483648", "14065839182", "16e07", "134985.0", "-12034" }; - foreach (string value in values) - { - try { - uint number = UInt32.Parse(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); - } - } - // The example displays the following output: - // +13230 --> 13230 - // -0 --> 0 - // 1,390,146: Bad Format - // $190,235,421,127: Bad Format - // 0xFA1B: Bad Format - // 163042 --> 163042 - // -10: Overflow - // 2147483648 --> 2147483648 - // 14065839182: Overflow - // 16e07: Bad Format - // 134985.0: Bad Format - // -12034: Overflow - // - } + foreach (string value in values) + { + try + { + uint number = uint.Parse(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"{value}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{value}: Overflow"); + } + } + // The example displays the following output: + // +13230 --> 13230 + // -0 --> 0 + // 1,390,146: Bad Format + // $190,235,421,127: Bad Format + // 0xFA1B: Bad Format + // 163042 --> 163042 + // -10: Overflow + // 2147483648 --> 2147483648 + // 14065839182: Overflow + // 16e07: Bad Format + // 134985.0: Bad Format + // -12034: Overflow + // + } } diff --git a/snippets/csharp/System/UInt32/Parse/parseex2.cs b/snippets/csharp/System/UInt32/Parse/parseex2.cs index 3879074fa19..7b0e9470ab5 100644 --- a/snippets/csharp/System/UInt32/Parse/parseex2.cs +++ b/snippets/csharp/System/UInt32/Parse/parseex2.cs @@ -2,39 +2,41 @@ using System; using System.Globalization; -public class Example +public class ParseExample2 { - public static void Main() - { - string[] values= { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", + public static void Run() + { + string[] values = { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", " +21499 ", "122153.00", "1e03ff", "91300.0e-2" }; - NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; - NumberStyles[] styles= { NumberStyles.None, whitespace, - NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, - NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, + NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; + NumberStyles[] styles = { NumberStyles.None, whitespace, + NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, + NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint }; - // Attempt to convert each number using each style combination. - foreach (string value in values) - { - Console.WriteLine("Attempting to convert '{0}':", value); - foreach (NumberStyles style in styles) - { - try { - uint number = UInt32.Parse(value, style); - Console.WriteLine(" {0}: {1}", style, number); - } - catch (FormatException) { - Console.WriteLine(" {0}: Bad Format", style); - } - catch (OverflowException) + // Attempt to convert each number using each style combination. + foreach (string value in values) + { + Console.WriteLine($"Attempting to convert '{value}':"); + foreach (NumberStyles style in styles) { - Console.WriteLine(" {0}: Overflow", value); - } - } - Console.WriteLine(); - } - } + try + { + uint number = uint.Parse(value, style); + Console.WriteLine($" {style}: {number}"); + } + catch (FormatException) + { + Console.WriteLine($" {style}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($" {value}: Overflow"); + } + } + Console.WriteLine(); + } + } } // The example displays the following output: // Attempting to convert ' 214309 ': @@ -43,60 +45,60 @@ public static void Main() // Integer, AllowTrailingSign: 214309 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1,064,181': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: 1064181 // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '(0)': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '10241+': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 10241 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' + 21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' +21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 21499 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '122153.00': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 122153 -// +// // Attempting to convert '1e03ff': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '91300.0e-2': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 913 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UInt32/Parse/parseex4.cs b/snippets/csharp/System/UInt32/Parse/parseex4.cs index b079e33ddef..43cc4a11b44 100644 --- a/snippets/csharp/System/UInt32/Parse/parseex4.cs +++ b/snippets/csharp/System/UInt32/Parse/parseex4.cs @@ -2,44 +2,44 @@ using System; using System.Globalization; -public class Example +public class ParseExample4 { - public static void Main() - { - string[] cultureNames= { "en-US", "fr-FR" }; - NumberStyles[] styles= { NumberStyles.Integer, + public static void Run() + { + string[] cultureNames = { "en-US", "fr-FR" }; + NumberStyles[] styles = { NumberStyles.Integer, NumberStyles.Integer | NumberStyles.AllowDecimalPoint }; - string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", + string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", "-103214,00", "104561.1", "104561,1" }; - - // Parse strings using each culture - foreach (string cultureName in cultureNames) - { - CultureInfo ci = new CultureInfo(cultureName); - Console.WriteLine("Parsing strings using the {0} culture", - ci.DisplayName); - // Use each style. - foreach (NumberStyles style in styles) - { - Console.WriteLine(" Style: {0}", style.ToString()); - // Parse each numeric string. - foreach (string value in values) + + // Parse strings using each culture + foreach (string cultureName in cultureNames) + { + CultureInfo ci = new(cultureName); + Console.WriteLine($"Parsing strings using the {ci.DisplayName} culture"); + // Use each style. + foreach (NumberStyles style in styles) { - try { - Console.WriteLine(" Converted '{0}' to {1}.", value, - UInt32.Parse(value, style, ci)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the UInt32 type.", - value); - } + Console.WriteLine($" Style: {style.ToString()}"); + // Parse each numeric string. + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {uint.Parse(value, style, ci)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the UInt32 type."); + } + } } - } - } - } + } + } } // The example displays the following output: // Parsing strings using the English (United States) culture @@ -76,4 +76,4 @@ public static void Main() // '-103214,00' is out of range of the UInt32 type. // Unable to parse '104561.1'. // '104561,1' is out of range of the UInt32 type. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UInt32/ToString/Program.cs b/snippets/csharp/System/UInt32/ToString/Program.cs new file mode 100644 index 00000000000..7af5a190e4e --- /dev/null +++ b/snippets/csharp/System/UInt32/ToString/Program.cs @@ -0,0 +1,4 @@ +UInt32ToStringExample1.Run(); +UInt32ToStringExample2.Run(); +UInt32ToStringExample3.Run(); +UInt32ToStringExample4.Run(); diff --git a/snippets/csharp/System/UInt32/ToString/Project.csproj b/snippets/csharp/System/UInt32/ToString/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt32/ToString/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt32/ToString/tostring1.cs b/snippets/csharp/System/UInt32/ToString/tostring1.cs index 0194e67d9af..61dc245107b 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring1.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring1.cs @@ -1,26 +1,25 @@ // using System; -public class Example +public class UInt32ToStringExample1 { - public static void Main() - { - uint value = 1632490; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); - Console.WriteLine(); - - // Define an array of format specifiers. - string[] formats = { "G", "C", "D", "F", "N", "X" }; - // Display value using the standard format specifiers. - foreach (string format in formats) - Console.WriteLine("{0} format specifier: {1,16}", - format, value.ToString(format)); - } + public static void Run() + { + uint value = 1632490; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); + Console.WriteLine(); + + // Define an array of format specifiers. + string[] formats = { "G", "C", "D", "F", "N", "X" }; + // Display value using the standard format specifiers. + foreach (string format in formats) + Console.WriteLine($"{format} format specifier: {value.ToString(format),16}"); + } } // The example displays the following output: // 1632490 -// +// // G format specifier: 1632490 // C format specifier: $1,632,490.00 // D format specifier: 1632490 diff --git a/snippets/csharp/System/UInt32/ToString/tostring2.cs b/snippets/csharp/System/UInt32/ToString/tostring2.cs index b10fee2ce2d..4cc6a2e9891 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring2.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring2.cs @@ -2,28 +2,26 @@ using System; using System.Globalization; -public class Example +public class UInt32ToStringExample2 { - public static void Main() - { - // Define an array of CultureInfo objects. - CultureInfo[] ci = { new CultureInfo("en-US"), - new CultureInfo("fr-FR"), - CultureInfo.InvariantCulture }; - uint value = 1870924; - Console.WriteLine(" {0,12} {1,12} {2,12}", - GetName(ci[0]), GetName(ci[1]), GetName(ci[2])); - Console.WriteLine(" {0,12} {1,12} {2,12}", - value.ToString(ci[0]), value.ToString(ci[1]), value.ToString(ci[2])); - } + public static void Run() + { + // Define an array of CultureInfo objects. + CultureInfo[] ci = { new CultureInfo("en-US"), + new CultureInfo("fr-FR"), + CultureInfo.InvariantCulture }; + uint value = 1870924; + Console.WriteLine($" {GetName(ci[0]),12} {GetName(ci[1]),12} {GetName(ci[2]),12}"); + Console.WriteLine($" {value.ToString(ci[0]),12} {value.ToString(ci[1]),12} {value.ToString(ci[2]),12}"); + } - private static string GetName(CultureInfo ci) - { - if (ci.Equals(CultureInfo.InvariantCulture)) - return "Invariant"; - else - return ci.Name; - } + private static string GetName(CultureInfo ci) + { + if (ci.Equals(CultureInfo.InvariantCulture)) + return "Invariant"; + else + return ci.Name; + } } // The example displays the following output: // en-US fr-FR Invariant diff --git a/snippets/csharp/System/UInt32/ToString/tostring3.cs b/snippets/csharp/System/UInt32/ToString/tostring3.cs index 297d0a1b02e..00260898a00 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring3.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring3.cs @@ -1,19 +1,19 @@ // using System; -using System.Globalization; -public class Example + +public class UInt32ToStringExample3 { - public static void Main() - { - uint value = 2179608; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "000000.0", "#.0", + public static void Run() + { + uint value = 2179608; + string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "000000.0", "#.0", "00000000;(0);**Zero**" }; - - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - } + + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + } } // The example displays the following output: // G: 2179608 diff --git a/snippets/csharp/System/UInt32/ToString/tostring4.cs b/snippets/csharp/System/UInt32/ToString/tostring4.cs index ffa9e04c388..0f522f30fb2 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring4.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring4.cs @@ -2,56 +2,54 @@ using System; using System.Globalization; -public class Example +public class UInt32ToStringExample4 { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), - CultureInfo.CreateSpecificCulture("fr-FR"), + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), + CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("es-ES") }; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - uint value = 2222402; - - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 18}", - specifier, culture.Name, - value.ToString(specifier, culture)); - Console.WriteLine(); - } - } + string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" }; + uint value = 2222402; + + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {value.ToString(specifier, culture),18}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 2222402 // G format using fr-FR culture: 2222402 // G format using es-ES culture: 2222402 -// +// // C format using en-US culture: $2,222,402.00 // C format using fr-FR culture: 2 222 402,00 € // C format using es-ES culture: 2.222.402,00 € -// +// // D4 format using en-US culture: 2222402 // D4 format using fr-FR culture: 2222402 // D4 format using es-ES culture: 2222402 -// +// // E2 format using en-US culture: 2.22E+006 // E2 format using fr-FR culture: 2,22E+006 // E2 format using es-ES culture: 2,22E+006 -// +// // F format using en-US culture: 2222402.00 // F format using fr-FR culture: 2222402,00 // F format using es-ES culture: 2222402,00 -// +// // N format using en-US culture: 2,222,402.00 // N format using fr-FR culture: 2 222 402,00 // N format using es-ES culture: 2.222.402,00 -// +// // P format using en-US culture: 222,240,200.00 % // P format using fr-FR culture: 222 240 200,00 % // P format using es-ES culture: 222.240.200,00 % -// +// // X2 format using en-US culture: 21E942 // X2 format using fr-FR culture: 21E942 // X2 format using es-ES culture: 21E942 diff --git a/snippets/csharp/System/UInt64/CompareTo/source.cs b/snippets/csharp/System/UInt64/CompareTo/source.cs index 068f462c181..52c992f0407 100644 --- a/snippets/csharp/System/UInt64/CompareTo/source.cs +++ b/snippets/csharp/System/UInt64/CompareTo/source.cs @@ -1,314 +1,314 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("G", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - - Console.ReadLine(); - } - } - // - /// - /// Temperature class stores the value as UInt64 - /// and delegates most of the functionality - /// to the UInt64 implementation. - /// - public class Temperature : IComparable, IFormattable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt64.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets +{ + class Launcher + { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("G", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + + Console.ReadLine(); + } + } + // + /// + /// Temperature class stores the value as UInt64 + /// and delegates most of the functionality + /// to the UInt64 implementation. + /// + public class Temperature : IComparable, IFormattable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ulong.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static ulong MinValue { - get { - return UInt64.MinValue; - } - } - - public static ulong MaxValue { - get { - return UInt64.MaxValue; - } - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static ulong MinValue => ulong.MinValue; + + public static ulong MaxValue => ulong.MaxValue; + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets3 +{ + // + public class Temperature : IComparable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = UInt64.Parse(s); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = ulong.Parse(s); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = UInt64.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = ulong.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = UInt64.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = ulong.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt64.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ulong.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } diff --git a/snippets/csharp/System/UInt64/Equals/Program.cs b/snippets/csharp/System/UInt64/Equals/Program.cs new file mode 100644 index 00000000000..3319f2f339f --- /dev/null +++ b/snippets/csharp/System/UInt64/Equals/Program.cs @@ -0,0 +1,3 @@ +UInt64EqualsObjectExample.Run(); +UInt64EqualsOverloadExample.Run(); +UInt64EqualsExample.Run(); diff --git a/snippets/csharp/System/UInt64/Equals/Project.csproj b/snippets/csharp/System/UInt64/Equals/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/Equals/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/Equals/equals1.cs b/snippets/csharp/System/UInt64/Equals/equals1.cs index d7efc60d198..6ba81b5abfb 100644 --- a/snippets/csharp/System/UInt64/Equals/equals1.cs +++ b/snippets/csharp/System/UInt64/Equals/equals1.cs @@ -1,23 +1,20 @@ // using System; -public class Example +public class UInt64EqualsObjectExample { - public static void Main() - { - object[] values = { (short) 10, (short) 20, 10, 20, + public static void Run() + { + object[] values = { (short) 10, (short) 20, 10, 20, 10L, 20L, 10D, 20D, (ushort) 10, (ushort) 20, 10U, 20U, 10ul, 20ul }; - UInt64 baseValue = 20; - String baseType = baseValue.GetType().Name; - - foreach (var value in values) - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", - baseValue, baseType, - value, value.GetType().Name, - baseValue.Equals(value)); - } + ulong baseValue = 20; + string baseType = baseValue.GetType().Name; + + foreach (object value in values) + Console.WriteLine($"{baseValue} ({baseType}) = {value} ({value.GetType().Name}): {baseValue.Equals(value)}"); + } } // The example displays the following output: // 20 (UInt64) = 10 (Int16): False @@ -34,4 +31,4 @@ public static void Main() // 20 (UInt64) = 20 (UInt32): False // 20 (UInt64) = 10 (UInt64): False // 20 (UInt64) = 20 (UInt64): True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UInt64/Equals/equalsoverl.cs b/snippets/csharp/System/UInt64/Equals/equalsoverl.cs index 3ecff88cf30..99e4b7384d2 100644 --- a/snippets/csharp/System/UInt64/Equals/equalsoverl.cs +++ b/snippets/csharp/System/UInt64/Equals/equalsoverl.cs @@ -1,52 +1,46 @@ // using System; -public class Example +public class UInt64EqualsOverloadExample { - static ulong value = 112; - - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); + static ulong value = 112; - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); + public static void Run() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); - int int1 = 112; - Console.WriteLine("value = int1: {0,19}", value.Equals(int1)); - TestObjectForEquality(int1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),19}"); + TestObjectForEquality(int1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); - uint uint1 = 112; - Console.WriteLine("value = uint1: {0,18}", value.Equals(uint1)); - TestObjectForEquality(uint1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}"); + TestObjectForEquality(ushort1); - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); + uint uint1 = 112; + Console.WriteLine($"value = uint1: {value.Equals(uint1),18}"); + TestObjectForEquality(uint1); - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } + + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/UInt64/Equals/uint64_equals.cs b/snippets/csharp/System/UInt64/Equals/uint64_equals.cs index e98b47116d2..e303f5ef7bc 100644 --- a/snippets/csharp/System/UInt64/Equals/uint64_equals.cs +++ b/snippets/csharp/System/UInt64/Equals/uint64_equals.cs @@ -1,23 +1,20 @@ // using System; -class Example +class UInt64EqualsExample { - public static void Main() - { - UInt64 value1 = 50; - UInt64 value2 = 50; + public static void Run() + { + ulong value1 = 50; + ulong value2 = 50; - // Display the values. - Console.WriteLine("value1: Type: {0} Value: {1}", - value1.GetType().Name, value1); - Console.WriteLine("value2: Type: {0} Value: {1}", - value2.GetType().Name, value2); + // Display the values. + Console.WriteLine($"value1: Type: {value1.GetType().Name} Value: {value1}"); + Console.WriteLine($"value2: Type: {value2.GetType().Name} Value: {value2}"); // Compare the two values. - Console.WriteLine("value1 and value2 are equal: {0}", - value1.Equals(value2)); - } + Console.WriteLine($"value1 and value2 are equal: {value1.Equals(value2)}"); + } } // The example displays the following output: // value1: Type: UInt64 Value: 50 diff --git a/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs b/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs index 8b8e3045eb6..a08ada6029a 100644 --- a/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs +++ b/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs @@ -2,42 +2,39 @@ public class ULongRangeExample { - public static void Main() - { - // - double decimalValue = -1.5; - ulong integerValue; - - // Discard fractional portion of Double value - double decimalInteger = Math.Floor(decimalValue); + public static void Main() + { + // + double decimalValue = -1.5; + ulong integerValue; - if (decimalInteger <= ulong.MaxValue && - decimalInteger >= ulong.MinValue) - { - integerValue = (ulong) decimalValue; - Console.WriteLine("Converted {0} to {1}.", decimalValue, integerValue); - } - else - { - ulong rangeLimit; - string relationship; - - if (decimalInteger > ulong.MaxValue) - { - rangeLimit = ulong.MaxValue; - relationship = "greater"; - } - else - { - rangeLimit = ulong.MinValue; - relationship = "less"; - } + // Discard fractional portion of Double value + double decimalInteger = Math.Floor(decimalValue); - Console.WriteLine("Conversion failure: {0} is {1} than {2}.", - decimalInteger, - relationship, - rangeLimit); - } - // - } + if (decimalInteger <= ulong.MaxValue && + decimalInteger >= ulong.MinValue) + { + integerValue = (ulong)decimalValue; + Console.WriteLine($"Converted {decimalValue} to {integerValue}."); + } + else + { + ulong rangeLimit; + string relationship; + + if (decimalInteger > ulong.MaxValue) + { + rangeLimit = ulong.MaxValue; + relationship = "greater"; + } + else + { + rangeLimit = ulong.MinValue; + relationship = "less"; + } + + Console.WriteLine($"Conversion failure: {decimalInteger} is {relationship} than {rangeLimit}."); + } + // + } } diff --git a/snippets/csharp/System/UInt64/Parse/Program.cs b/snippets/csharp/System/UInt64/Parse/Program.cs new file mode 100644 index 00000000000..a463149ef55 --- /dev/null +++ b/snippets/csharp/System/UInt64/Parse/Program.cs @@ -0,0 +1,3 @@ +UInt64ParseExample1.Run(); +UInt64ParseExample2.Run(); +UInt64ParseExample4.Run(); diff --git a/snippets/csharp/System/UInt64/Parse/Project.csproj b/snippets/csharp/System/UInt64/Parse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/Parse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/Parse/parse1.cs b/snippets/csharp/System/UInt64/Parse/parse1.cs index 0b59d80938a..7633545766a 100644 --- a/snippets/csharp/System/UInt64/Parse/parse1.cs +++ b/snippets/csharp/System/UInt64/Parse/parse1.cs @@ -1,38 +1,41 @@ using System; -public class Example +public class UInt64ParseExample1 { - public static void Main() - { - // - string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", + public static void Run() + { + // + string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", "0xFA1B", "163042", "-10", "14065839182", "16e07", "134985.0", "-12034" }; - foreach (string value in values) - { - try { - ulong number = UInt64.Parse(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); - } - } - // The example displays the following output: - // +13230 --> 13230 - // -0 --> 0 - // 1,390,146: Bad Format - // $190,235,421,127: Bad Format - // 0xFA1B: Bad Format - // 163042 --> 163042 - // -10: Overflow - // 14065839182 --> 14065839182 - // 16e07: Bad Format - // 134985.0: Bad Format - // -12034: Overflow - // - } + foreach (string value in values) + { + try + { + ulong number = ulong.Parse(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"{value}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{value}: Overflow"); + } + } + // The example displays the following output: + // +13230 --> 13230 + // -0 --> 0 + // 1,390,146: Bad Format + // $190,235,421,127: Bad Format + // 0xFA1B: Bad Format + // 163042 --> 163042 + // -10: Overflow + // 14065839182 --> 14065839182 + // 16e07: Bad Format + // 134985.0: Bad Format + // -12034: Overflow + // + } } diff --git a/snippets/csharp/System/UInt64/Parse/parseex2.cs b/snippets/csharp/System/UInt64/Parse/parseex2.cs index 3f704399295..dd8db283108 100644 --- a/snippets/csharp/System/UInt64/Parse/parseex2.cs +++ b/snippets/csharp/System/UInt64/Parse/parseex2.cs @@ -2,39 +2,41 @@ using System; using System.Globalization; -public class Example +public class UInt64ParseExample2 { - public static void Main() - { - string[] values= { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", + public static void Run() + { + string[] values = { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", " +21499 ", "122153.00", "1e03ff", "91300.0e-2" }; - NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; - NumberStyles[] styles= { NumberStyles.None, whitespace, - NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, - NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, + NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; + NumberStyles[] styles = { NumberStyles.None, whitespace, + NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, + NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint }; - // Attempt to convert each number using each style combination. - foreach (string value in values) - { - Console.WriteLine("Attempting to convert '{0}':", value); - foreach (NumberStyles style in styles) - { - try { - ulong number = UInt64.Parse(value, style); - Console.WriteLine(" {0}: {1}", style, number); - } - catch (FormatException) { - Console.WriteLine(" {0}: Bad Format", style); - } - catch (OverflowException) + // Attempt to convert each number using each style combination. + foreach (string value in values) + { + Console.WriteLine($"Attempting to convert '{value}':"); + foreach (NumberStyles style in styles) { - Console.WriteLine(" {0}: Overflow", value); - } - } - Console.WriteLine(); - } - } + try + { + ulong number = ulong.Parse(value, style); + Console.WriteLine($" {style}: {number}"); + } + catch (FormatException) + { + Console.WriteLine($" {style}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($" {value}: Overflow"); + } + } + Console.WriteLine(); + } + } } // The example displays the following output: // Attempting to convert ' 214309 ': @@ -43,56 +45,56 @@ public static void Main() // Integer, AllowTrailingSign: 214309 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1,064,181': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: 1064181 // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '(0)': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '10241+': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 10241 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' + 21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' +21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 21499 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '122153.00': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 122153 -// +// // Attempting to convert '1e03ff': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '91300.0e-2': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format diff --git a/snippets/csharp/System/UInt64/Parse/parseex4.cs b/snippets/csharp/System/UInt64/Parse/parseex4.cs index aff85eb102b..caa5e31c30f 100644 --- a/snippets/csharp/System/UInt64/Parse/parseex4.cs +++ b/snippets/csharp/System/UInt64/Parse/parseex4.cs @@ -2,44 +2,44 @@ using System; using System.Globalization; -public class Example +public class UInt64ParseExample4 { - public static void Main() - { - string[] cultureNames= { "en-US", "fr-FR" }; - NumberStyles[] styles= { NumberStyles.Integer, + public static void Run() + { + string[] cultureNames = { "en-US", "fr-FR" }; + NumberStyles[] styles = { NumberStyles.Integer, NumberStyles.Integer | NumberStyles.AllowDecimalPoint }; - string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", + string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", "-103214,00", "104561.1", "104561,1" }; - - // Parse strings using each culture - foreach (string cultureName in cultureNames) - { - CultureInfo ci = new CultureInfo(cultureName); - Console.WriteLine("Parsing strings using the {0} culture", - ci.DisplayName); - // Use each style. - foreach (NumberStyles style in styles) - { - Console.WriteLine(" Style: {0}", style.ToString()); - // Parse each numeric string. - foreach (string value in values) + + // Parse strings using each culture + foreach (string cultureName in cultureNames) + { + CultureInfo ci = new(cultureName); + Console.WriteLine($"Parsing strings using the {ci.DisplayName} culture"); + // Use each style. + foreach (NumberStyles style in styles) { - try { - Console.WriteLine(" Converted '{0}' to {1}.", value, - UInt64.Parse(value, style, ci)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the UInt64 type.", - value); - } + Console.WriteLine($" Style: {style.ToString()}"); + // Parse each numeric string. + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {ulong.Parse(value, style, ci)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the UInt64 type."); + } + } } - } - } - } + } + } } // The example displays the following output: // Style: Integer diff --git a/snippets/csharp/System/UInt64/ToString/Program.cs b/snippets/csharp/System/UInt64/ToString/Program.cs new file mode 100644 index 00000000000..442730bd75e --- /dev/null +++ b/snippets/csharp/System/UInt64/ToString/Program.cs @@ -0,0 +1,4 @@ +UInt64ToStringExample1.Run(); +UInt64ToStringExample2.Run(); +UInt64ToStringExample3.Run(); +UInt64ToStringExample4.Run(); diff --git a/snippets/csharp/System/UInt64/ToString/Project.csproj b/snippets/csharp/System/UInt64/ToString/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/ToString/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/ToString/tostring1.cs b/snippets/csharp/System/UInt64/ToString/tostring1.cs index a5f35b12be5..9e02244ebcf 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring1.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring1.cs @@ -1,26 +1,25 @@ // using System; -public class Example +public class UInt64ToStringExample1 { - public static void Main() - { - ulong value = 163249057; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); - Console.WriteLine(); - - // Define an array of format specifiers. - string[] formats = { "G", "C", "D", "F", "N", "X" }; - // Display value using the standard format specifiers. - foreach (string format in formats) - Console.WriteLine("{0} format specifier: {1,16}", - format, value.ToString(format)); - } + public static void Run() + { + ulong value = 163249057; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); + Console.WriteLine(); + + // Define an array of format specifiers. + string[] formats = { "G", "C", "D", "F", "N", "X" }; + // Display value using the standard format specifiers. + foreach (string format in formats) + Console.WriteLine($"{format} format specifier: {value.ToString(format),16}"); + } } // The example displays the following output: // 163249057 -// +// // G format specifier: 163249057 // C format specifier: $163,249,057.00 // D format specifier: 163249057 diff --git a/snippets/csharp/System/UInt64/ToString/tostring2.cs b/snippets/csharp/System/UInt64/ToString/tostring2.cs index 9aea3c57d79..53daa1d01eb 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring2.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring2.cs @@ -2,28 +2,26 @@ using System; using System.Globalization; -public class Example +public class UInt64ToStringExample2 { - public static void Main() - { - // Define an array of CultureInfo objects. - CultureInfo[] ci = { new CultureInfo("en-US"), - new CultureInfo("fr-FR"), - CultureInfo.InvariantCulture }; - ulong value = 18709243; - Console.WriteLine(" {0,12} {1,12} {2,12}", - GetName(ci[0]), GetName(ci[1]), GetName(ci[2])); - Console.WriteLine(" {0,12} {1,12} {2,12}", - value.ToString(ci[0]), value.ToString(ci[1]), value.ToString(ci[2])); - } + public static void Run() + { + // Define an array of CultureInfo objects. + CultureInfo[] ci = { new CultureInfo("en-US"), + new CultureInfo("fr-FR"), + CultureInfo.InvariantCulture }; + ulong value = 18709243; + Console.WriteLine($" {GetName(ci[0]),12} {GetName(ci[1]),12} {GetName(ci[2]),12}"); + Console.WriteLine($" {value.ToString(ci[0]),12} {value.ToString(ci[1]),12} {value.ToString(ci[2]),12}"); + } - private static string GetName(CultureInfo ci) - { - if (ci.Equals(CultureInfo.InvariantCulture)) - return "Invariant"; - else - return ci.Name; - } + private static string GetName(CultureInfo ci) + { + if (ci.Equals(CultureInfo.InvariantCulture)) + return "Invariant"; + else + return ci.Name; + } } // The example displays the following output: // en-US fr-FR Invariant diff --git a/snippets/csharp/System/UInt64/ToString/tostring3.cs b/snippets/csharp/System/UInt64/ToString/tostring3.cs index ceea836f284..62fcfd81044 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring3.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring3.cs @@ -1,19 +1,19 @@ // using System; -using System.Globalization; -public class Example + +public class UInt64ToStringExample3 { - public static void Main() - { - ulong value = 217960834; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "000000.0", "#.0", + public static void Run() + { + ulong value = 217960834; + string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "000000.0", "#.0", "00000000;(0);**Zero**" }; - - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - } + + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + } } // The example displays the following output: // G: 217960834 diff --git a/snippets/csharp/System/UInt64/ToString/tostring4.cs b/snippets/csharp/System/UInt64/ToString/tostring4.cs index 2de875b7f2f..c625d786229 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring4.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring4.cs @@ -2,26 +2,24 @@ using System; using System.Globalization; -public class Example +public class UInt64ToStringExample4 { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("es-ES") }; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - ulong value = 22224021; + string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" }; + ulong value = 22224021; - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 18}", - specifier, culture.Name, - value.ToString(specifier, culture)); - Console.WriteLine(); - } - } + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {value.ToString(specifier, culture),18}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 22224021 diff --git a/snippets/csharp/System/UInt64/TryParse/Program.cs b/snippets/csharp/System/UInt64/TryParse/Program.cs new file mode 100644 index 00000000000..afaba9c2d4b --- /dev/null +++ b/snippets/csharp/System/UInt64/TryParse/Program.cs @@ -0,0 +1,2 @@ +UInt64TryParseExample1.Run(); +UInt64TryParseExample2.Run(); diff --git a/snippets/csharp/System/UInt64/TryParse/Project.csproj b/snippets/csharp/System/UInt64/TryParse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/TryParse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/TryParse/tryparse1.cs b/snippets/csharp/System/UInt64/TryParse/tryparse1.cs index a50c2947877..3225f876e7c 100644 --- a/snippets/csharp/System/UInt64/TryParse/tryparse1.cs +++ b/snippets/csharp/System/UInt64/TryParse/tryparse1.cs @@ -1,35 +1,35 @@ using System; -public class Example +public class UInt64TryParseExample1 { - public static void Main() - { - // - string[] numericStrings = { "1293.8", "+1671.7", "28347.", - " 33113684 ", "(0)", "-0", "+1293617", - "18-", "119870", "31,024", " 3127094 ", + public static void Run() + { + // + string[] numericStrings = { "1293.8", "+1671.7", "28347.", + " 33113684 ", "(0)", "-0", "+1293617", + "18-", "119870", "31,024", " 3127094 ", "00700000" }; - ulong number; - foreach (string numericString in numericStrings) - { - if (UInt64.TryParse(numericString, out number)) - Console.WriteLine("Converted '{0}' to {1}.", numericString, number); - else - Console.WriteLine("Cannot convert '{0}' to a UInt64.", numericString); - } - // The example displays the following output: - // Cannot convert '1293.8' to a UInt64. - // Cannot convert '+1671.7' to a UInt64. - // Cannot convert '28347.' to a UInt64. - // Converted ' 33113684 ' to 33113684. - // Cannot convert '(0)' to a UInt64. - // Converted '-0' to 0. - // Converted '+1293617' to 1293617. - // Cannot convert '18-' to a UInt64. - // Converted '119870' to 119870. - // Cannot convert '31,024' to a UInt64. - // Converted ' 3127094 ' to 3127094. - // Converted '0070000' to 70000. - // - } + ulong number; + foreach (string numericString in numericStrings) + { + if (ulong.TryParse(numericString, out number)) + Console.WriteLine($"Converted '{numericString}' to {number}."); + else + Console.WriteLine($"Cannot convert '{numericString}' to a UInt64."); + } + // The example displays the following output: + // Cannot convert '1293.8' to a UInt64. + // Cannot convert '+1671.7' to a UInt64. + // Cannot convert '28347.' to a UInt64. + // Converted ' 33113684 ' to 33113684. + // Cannot convert '(0)' to a UInt64. + // Converted '-0' to 0. + // Converted '+1293617' to 1293617. + // Cannot convert '18-' to a UInt64. + // Converted '119870' to 119870. + // Cannot convert '31,024' to a UInt64. + // Converted ' 3127094 ' to 3127094. + // Converted '0070000' to 70000. + // + } } diff --git a/snippets/csharp/System/UInt64/TryParse/tryparse2.cs b/snippets/csharp/System/UInt64/TryParse/tryparse2.cs index 895259d975f..0a7e8271dcd 100644 --- a/snippets/csharp/System/UInt64/TryParse/tryparse2.cs +++ b/snippets/csharp/System/UInt64/TryParse/tryparse2.cs @@ -2,56 +2,56 @@ using System; using System.Globalization; -public class Example +public class UInt64TryParseExample2 { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "2106034"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-10603"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "29103674.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "10345.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Run() + { + string numericString; + NumberStyles styles; - numericString = "41792210E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "9112E-01"; - CallTryParse(numericString, styles); - - numericString = "312E01"; - CallTryParse(numericString, styles); - - numericString = "FFC86DA1"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8F8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - ulong number; - bool result = UInt64.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "2106034"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-10603"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "29103674.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10345.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "41792210E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "9112E-01"; + CallTryParse(numericString, styles); + + numericString = "312E01"; + CallTryParse(numericString, styles); + + numericString = "FFC86DA1"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8F8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + ulong number; + bool result = ulong.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '2106034' to 2106034. diff --git a/snippets/csharp/System/UIntPtr/Add/add1.cs b/snippets/csharp/System/UIntPtr/Add/add1.cs index dc0af559267..141d744bd1b 100644 --- a/snippets/csharp/System/UIntPtr/Add/add1.cs +++ b/snippets/csharp/System/UIntPtr/Add/add1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - UIntPtr ptr = (UIntPtr) arr[0]; - for (int ctr = 0; ctr < arr.Length; ctr++) - { - UIntPtr newPtr = UIntPtr.Add(ptr, ctr); - Console.Write("{0} ", newPtr); - } - } + public static void Main() + { + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[0]; + for (int ctr = 0; ctr < arr.Length; ctr++) + { + UIntPtr newPtr = UIntPtr.Add(ptr, ctr); + Console.Write($"{newPtr} "); + } + } } // The example displays the following output: // 1 2 3 4 5 6 7 8 9 10 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs b/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs index 30d39b365d2..2811102f504 100644 --- a/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs +++ b/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - UIntPtr ptr = (UIntPtr) arr[arr.GetUpperBound(0)]; - for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) - { - UIntPtr newPtr = UIntPtr.Subtract(ptr, ctr); - Console.Write("{0} ", newPtr); - } - } + public static void Main() + { + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[arr.GetUpperBound(0)]; + for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) + { + UIntPtr newPtr = UIntPtr.Subtract(ptr, ctr); + Console.Write($"{newPtr} "); + } + } } // The example displays the following output: // 10 9 8 7 6 5 4 3 2 1 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UIntPtr/op_Addition/Program.cs b/snippets/csharp/System/UIntPtr/op_Addition/Program.cs new file mode 100644 index 00000000000..5114f22057c --- /dev/null +++ b/snippets/csharp/System/UIntPtr/op_Addition/Program.cs @@ -0,0 +1,2 @@ +UIntPtrAdditionExample.Run(); +UIntPtrSubtractionExample.Run(); diff --git a/snippets/csharp/System/UIntPtr/op_Addition/Project.csproj b/snippets/csharp/System/UIntPtr/op_Addition/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UIntPtr/op_Addition/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs b/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs index 8d5ff254ac6..50714f4911b 100644 --- a/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs +++ b/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs @@ -1,17 +1,17 @@ using System; -public class Example +public class UIntPtrAdditionExample { - public static void Main() - { - // - int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - UIntPtr ptr = (UIntPtr) arr[0]; - for (int ctr = 0; ctr < arr.Length; ctr++) - { - UIntPtr newPtr = ptr + ctr; - Console.WriteLine(newPtr); - } - // - } + public static void Run() + { + // + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[0]; + for (int ctr = 0; ctr < arr.Length; ctr++) + { + UIntPtr newPtr = ptr + (nuint)ctr; + Console.WriteLine(newPtr); + } + // + } } diff --git a/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs b/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs index 22a4c7a5adf..3bfd2eadd0d 100644 --- a/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs +++ b/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs @@ -1,17 +1,17 @@ using System; -public class Example +public class UIntPtrSubtractionExample { - public static void Main() - { - // - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - UIntPtr ptr = (UIntPtr) arr[arr.GetUpperBound(0)]; - for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) - { - UIntPtr newPtr = ptr - ctr; - Console.Write("{0} ", newPtr); - } - // - } + public static void Run() + { + // + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[arr.GetUpperBound(0)]; + for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) + { + UIntPtr newPtr = ptr - (nuint)ctr; + Console.Write($"{newPtr} "); + } + // + } } diff --git a/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs b/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs index 4b5b6eca616..8f2e06f9164 100644 --- a/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs +++ b/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs @@ -4,30 +4,34 @@ public class Example { - public static void Main() - { - string filePath = @".\ROFile.txt"; - if (!File.Exists(filePath)) - File.Create(filePath); - // Keep existing attributes, and set ReadOnly attribute. - File.SetAttributes(filePath, - (new FileInfo(filePath)).Attributes | FileAttributes.ReadOnly); + public static void Main() + { + string filePath = @".\ROFile.txt"; + if (!File.Exists(filePath)) + File.Create(filePath).Dispose(); - StreamWriter sw = null; - try { - sw = new StreamWriter(filePath); - sw.Write("Test"); - } - catch (UnauthorizedAccessException) { - FileAttributes attr = (new FileInfo(filePath)).Attributes; - Console.Write("UnAuthorizedAccessException: Unable to access file. "); - if ((attr & FileAttributes.ReadOnly) > 0) - Console.Write("The file is read-only."); - } - finally { - if (sw != null) sw.Close(); - } - } + // Keep existing attributes, and set ReadOnly attribute. + File.SetAttributes(filePath, + (new FileInfo(filePath)).Attributes | FileAttributes.ReadOnly); + + StreamWriter sw = null; + try + { + sw = new(filePath); + sw.Write("Test"); + } + catch (UnauthorizedAccessException) + { + FileAttributes attr = (new FileInfo(filePath)).Attributes; + Console.Write("UnAuthorizedAccessException: Unable to access file. "); + if ((attr & FileAttributes.ReadOnly) > 0) + Console.Write("The file is read-only."); + } + finally + { + if (sw != null) sw.Close(); + } + } } // The example displays the following output: // UnAuthorizedAccessException: Unable to access file. The file is read-only. diff --git a/snippets/csharp/System/Uri/.ctor/Project.csproj b/snippets/csharp/System/Uri/.ctor/Project.csproj new file mode 100644 index 00000000000..4a6d98d26b7 --- /dev/null +++ b/snippets/csharp/System/Uri/.ctor/Project.csproj @@ -0,0 +1,9 @@ + + + + Exe + net10.0-windows + true + + + diff --git a/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs b/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs index a11001351b8..0b99914c193 100644 --- a/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs +++ b/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs @@ -1,7 +1,7 @@ using System; -using System.Net; -using System.Text; -using System.Threading; + + + namespace Example { @@ -36,19 +36,23 @@ private static void SampleTryCreate() string addressString = "catalog/shownew.htm?date=today"; // Parse the string and create a new Uri instance, if possible. Uri result = null; - if (Uri.TryCreate(addressString, UriKind.RelativeOrAbsolute, out result)) { + if (Uri.TryCreate(addressString, UriKind.RelativeOrAbsolute, out result)) + { // The call was successful. Write the URI address to the console. Console.Write(result.ToString()); // Check whether new Uri instance is absolute or relative. - if (result.IsAbsoluteUri) { + if (result.IsAbsoluteUri) + { Console.WriteLine(" is an absolute Uri."); } - else { + else + { Console.WriteLine(" is a relative Uri."); } } - else { - // Let the user know that the call failed. + else + { + // Let the user know that the call failed. Console.WriteLine("addressString could not be parsed as a URI " + "address."); } @@ -60,18 +64,18 @@ private static void SampleConstructor() { // // Create an absolute Uri from a string. - Uri absoluteUri = new Uri("http://www.contoso.com/"); + Uri absoluteUri = new("http://www.contoso.com/"); // Create a relative Uri from a string. allowRelative = true to allow for // creating a relative Uri. - Uri relativeUri = new Uri("/catalog/shownew.htm?date=today", UriKind.Relative); + Uri relativeUri = new("/catalog/shownew.htm?date=today", UriKind.Relative); // Check whether the new Uri is absolute or relative. if (!relativeUri.IsAbsoluteUri) - Console.WriteLine("{0} is a relative Uri.", relativeUri); + Console.WriteLine($"{relativeUri} is a relative Uri."); // Create a new Uri from an absolute Uri and a relative Uri. - Uri combinedUri = new Uri(absoluteUri, relativeUri); + Uri combinedUri = new(absoluteUri, relativeUri); Console.WriteLine(combinedUri.AbsoluteUri); // } @@ -81,7 +85,7 @@ private static void SampleOriginalString() { // // Create a new Uri from a string address. - Uri uriAddress = new Uri("HTTP://www.ConToso.com:80//thick%20and%20thin.htm"); + Uri uriAddress = new("HTTP://www.ConToso.com:80//thick%20and%20thin.htm"); // Write the new Uri to the console and note the difference in the two values. // ToString() gives the canonical version. OriginalString gives the original @@ -100,7 +104,7 @@ private static void SampleDNSSafeHost() { // // Create new Uri using a string address. - Uri address = new Uri("http://[fe80::200:39ff:fe36:1a2d%254]/temp/example.htm"); + Uri address = new("http://[fe80::200:39ff:fe36:1a2d%254]/temp/example.htm"); // Make the address DNS safe. @@ -117,17 +121,17 @@ private static void SampleOperatorEqual() { // // Create some Uris. - Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); - Uri address2 = new Uri("http://www.contoso.com/index.htm"); - Uri address3 = new Uri("http://www.contoso.com/index.htm?date=today"); + Uri address1 = new("http://www.contoso.com/index.htm#search"); + Uri address2 = new("http://www.contoso.com/index.htm"); + Uri address3 = new("http://www.contoso.com/index.htm?date=today"); // The first two are equal because the fragment is ignored. if (address1 == address2) - Console.WriteLine("{0} is equal to {1}", address1.ToString(), address2.ToString()); + Console.WriteLine($"{address1.ToString()} is equal to {address2.ToString()}"); // The second two are not equal. if (address2 != address3) - Console.WriteLine("{0} is not equal to {1}", address2.ToString(), address3.ToString()); + Console.WriteLine($"{address2.ToString()} is not equal to {address3.ToString()}"); // } @@ -136,14 +140,14 @@ private static void SampleIsBaseOf() { // // Create a base Uri. - Uri baseUri = new Uri("http://www.contoso.com/"); + Uri baseUri = new("http://www.contoso.com/"); // Create a new Uri from a string. - Uri uriAddress = new Uri("http://www.contoso.com/index.htm?date=today"); + Uri uriAddress = new("http://www.contoso.com/index.htm?date=today"); // Determine whether BaseUri is a base of UriAddress. if (baseUri.IsBaseOf(uriAddress)) - Console.WriteLine("{0} is the base of {1}", baseUri, uriAddress); + Console.WriteLine($"{baseUri} is the base of {uriAddress}"); // } } diff --git a/snippets/csharp/System/Uri/.ctor/source.cs b/snippets/csharp/System/Uri/.ctor/source.cs index 5e9260532e0..1bcfd2903c8 100644 --- a/snippets/csharp/System/Uri/.ctor/source.cs +++ b/snippets/csharp/System/Uri/.ctor/source.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriConstructorForm1 : Form { - protected void Method() - { -// -Uri myUri = new Uri("http://www.contoso.com/"); + protected void Method() + { + // + Uri myUri = new("http://www.contoso.com/"); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/.ctor/source2.cs b/snippets/csharp/System/Uri/.ctor/source2.cs index 32d5bcda07c..1ea7c279ce7 100644 --- a/snippets/csharp/System/Uri/.ctor/source2.cs +++ b/snippets/csharp/System/Uri/.ctor/source2.cs @@ -1,19 +1,16 @@ using System; -using System.Data; -using System.Security.Principal; -using System.IO; using System.Windows.Forms; -public class Form1: Form +public class UriConstructorForm2 : Form { - protected void Method() - { -// -Uri baseUri = new Uri("http://www.contoso.com"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm"); + protected void Method() + { + // + Uri baseUri = new("http://www.contoso.com"); + Uri myUri = new(baseUri, "catalog/shownew.htm"); -Console.WriteLine(myUri.ToString()); + Console.WriteLine(myUri.ToString()); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/AbsolutePath/source.cs b/snippets/csharp/System/Uri/AbsolutePath/source.cs index 9faa6f489aa..828ce4cca8f 100644 --- a/snippets/csharp/System/Uri/AbsolutePath/source.cs +++ b/snippets/csharp/System/Uri/AbsolutePath/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,11 +8,11 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.AbsolutePath); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/AbsoluteUri/source.cs b/snippets/csharp/System/Uri/AbsoluteUri/source.cs index 280a9a037a9..10b68dec3d2 100644 --- a/snippets/csharp/System/Uri/AbsoluteUri/source.cs +++ b/snippets/csharp/System/Uri/AbsoluteUri/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,9 +8,9 @@ public class Form1 protected void Method() { // - Uri baseUri= new Uri("http://www.contoso.com"); - Uri myUri = new Uri(baseUri,"catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.AbsoluteUri); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/Authority/source.cs b/snippets/csharp/System/Uri/Authority/source.cs index 6ea24db8682..77a296ced25 100644 --- a/snippets/csharp/System/Uri/Authority/source.cs +++ b/snippets/csharp/System/Uri/Authority/source.cs @@ -1,18 +1,18 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 { - protected void Method() - { -// - Uri baseUri = new Uri("http://www.contoso.com:8080/"); - Uri myUri = new Uri(baseUri,"shownew.htm?date=today"); + protected void Method() + { + // + Uri baseUri = new("http://www.contoso.com:8080/"); + Uri myUri = new(baseUri, "shownew.htm?date=today"); - Console.WriteLine(myUri.Authority); + Console.WriteLine(myUri.Authority); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/CheckHostName/source.cs b/snippets/csharp/System/Uri/CheckHostName/source.cs index 837e5c6c6b1..73d988bfc0c 100644 --- a/snippets/csharp/System/Uri/CheckHostName/source.cs +++ b/snippets/csharp/System/Uri/CheckHostName/source.cs @@ -1,15 +1,15 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 { - protected void Method() - { -// -Console.WriteLine(Uri.CheckHostName("www.contoso.com")); + protected void Method() + { + // + Console.WriteLine(Uri.CheckHostName("www.contoso.com")); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs b/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs index 05f60b1cd08..64e398d601a 100644 --- a/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs +++ b/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs @@ -1,8 +1,8 @@ using System; -using System.Net; -using System.Text; -using System.Threading; -using System.Runtime.Serialization; + + + + namespace Example { @@ -38,9 +38,9 @@ public static void Main() private static void SampleToString() { - // + // // Create a new Uri from a string address. - Uri uriAddress = new Uri("HTTP://www.Contoso.com:80/thick%20and%20thin.htm"); + Uri uriAddress = new("HTTP://www.Contoso.com:80/thick%20and%20thin.htm"); // Write the new Uri to the console and note the difference in the two values. // ToString() gives the canonical version. OriginalString gives the orginal @@ -51,190 +51,189 @@ private static void SampleToString() // The following outputs "HTTP://www.Contoso.com:80/thick%20and%20thin.htm". Console.WriteLine(uriAddress.OriginalString); - // + // } private static void SampleEquals() { - // + // // Create some Uris. - Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); - Uri address2 = new Uri("http://www.contoso.com/index.htm"); + Uri address1 = new("http://www.contoso.com/index.htm#search"); + Uri address2 = new("http://www.contoso.com/index.htm"); if (address1.Equals(address2)) Console.WriteLine("The two addresses are equal"); else Console.WriteLine("The two addresses are not equal"); // Will output "The two addresses are equal" - // + // } private static void GetParts() { - // + // // Create Uri - Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search"); + Uri uriAddress = new("http://www.contoso.com/index.htm#search"); Console.WriteLine(uriAddress.Fragment); - Console.WriteLine("Uri {0} the default port ", uriAddress.IsDefaultPort ? "uses" : "does not use"); + Console.WriteLine($"Uri {(uriAddress.IsDefaultPort ? "uses" : "does not use")} the default port "); - Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Path)); - Console.WriteLine("Hash code {0}", uriAddress.GetHashCode()); + Console.WriteLine($"The path of this Uri is {uriAddress.GetLeftPart(UriPartial.Path)}"); + Console.WriteLine($"Hash code {uriAddress.GetHashCode()}"); // The example displays output similar to the following: // #search // Uri uses the default port // The path of this Uri is http://www.contoso.com/index.htm // Hash code -988419291 - // - // - Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm"); - Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0], uriAddress1.Segments[1], uriAddress1.Segments[2]); - // - - // - Uri uriAddress2 = new Uri("file://server/filename.ext"); + // + // + Uri uriAddress1 = new("http://www.contoso.com/title/index.htm"); + Console.WriteLine($"The parts are {uriAddress1.Segments[0]}, {uriAddress1.Segments[1]}, {uriAddress1.Segments[2]}"); + // + + // + Uri uriAddress2 = new("file://server/filename.ext"); Console.WriteLine(uriAddress2.LocalPath); - Console.WriteLine("Uri {0} a UNC path", uriAddress2.IsUnc ? "is" : "is not"); - Console.WriteLine("Uri {0} a local host", uriAddress2.IsLoopback ? "is" : "is not"); - Console.WriteLine("Uri {0} a file", uriAddress2.IsFile ? "is" : "is not"); + Console.WriteLine($"Uri {(uriAddress2.IsUnc ? "is" : "is not")} a UNC path"); + Console.WriteLine($"Uri {(uriAddress2.IsLoopback ? "is" : "is not")} a local host"); + Console.WriteLine($"Uri {(uriAddress2.IsFile ? "is" : "is not")} a file"); // The example displays the following output: // \\server\filename.ext // Uri is a UNC path // Uri is not a local host // Uri is a file - // + // } private static void HexConversions() { - // - char testChar = 'e'; + // + char testChar = 'e'; if (Uri.IsHexDigit(testChar)) - Console.WriteLine("'{0}' is the hexadecimal representation of {1}", testChar, Uri.FromHex(testChar)); + Console.WriteLine($"'{testChar}' is the hexadecimal representation of {Uri.FromHex(testChar)}"); else - Console.WriteLine("'{0}' is not a hexadecimal character", testChar); + Console.WriteLine($"'{testChar}' is not a hexadecimal character"); string returnString = Uri.HexEscape(testChar); - Console.WriteLine("The hexadecimal value of '{0}' is {1}", testChar, returnString); - // + Console.WriteLine($"The hexadecimal value of '{testChar}' is {returnString}"); + // - // + // string testString = "%75"; int index = 0; if (Uri.IsHexEncoding(testString, index)) - Console.WriteLine("The character is {0}", Uri.HexUnescape(testString, ref index)); + Console.WriteLine($"The character is {Uri.HexUnescape(testString, ref index)}"); else - Console.WriteLine("The character is not hexadecimal encoded"); - // + Console.WriteLine("The character is not hexadecimal encoded"); + // } // MakeRelative private static void SampleMakeRelative() { - // + // // Create a base Uri. - Uri address1 = new Uri("http://www.contoso.com/"); + Uri address1 = new("http://www.contoso.com/"); // Create a new Uri from a string. - Uri address2 = new Uri("http://www.contoso.com/index.htm?date=today"); + Uri address2 = new("http://www.contoso.com/index.htm?date=today"); // Determine the relative Uri. - Console.WriteLine("The difference is {0}", address1.MakeRelativeUri(address2)); - // + Console.WriteLine($"The difference is {address1.MakeRelativeUri(address2)}"); + // } //CheckSchemeName private static void SampleCheckSchemeName() { - // - Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); - Console.WriteLine("address 1 {0} a valid scheme name", - Uri.CheckSchemeName(address1.Scheme) ? " has" : " does not have"); + // + Uri address1 = new("http://www.contoso.com/index.htm#search"); + Console.WriteLine($"address 1 {(Uri.CheckSchemeName(address1.Scheme) ? " has" : " does not have")} a valid scheme name"); if (address1.Scheme == Uri.UriSchemeHttp) Console.WriteLine("Uri is HTTP type"); Console.WriteLine(address1.HostNameType); - // + // - // - Uri address2 = new Uri("file://server/filename.ext"); + // + Uri address2 = new("file://server/filename.ext"); if (address2.Scheme == Uri.UriSchemeFile) Console.WriteLine("Uri is a file"); - // + // Console.WriteLine(address2.HostNameType); - // - Uri address3 = new Uri("mailto:user@contoso.com?subject=uri"); + // + Uri address3 = new("mailto:user@contoso.com?subject=uri"); if (address3.Scheme == Uri.UriSchemeMailto) Console.WriteLine("Uri is an email address"); - // + // - // - Uri address4 = new Uri("news:123456@contoso.com"); + // + Uri address4 = new("news:123456@contoso.com"); if (address4.Scheme == Uri.UriSchemeNews) Console.WriteLine("Uri is an Internet news group"); - // + // - // - Uri address5 = new Uri("nntp://news.contoso.com/123456@contoso.com"); + // + Uri address5 = new("nntp://news.contoso.com/123456@contoso.com"); if (address5.Scheme == Uri.UriSchemeNntp) Console.WriteLine("Uri is nntp protocol"); - // + // - // - Uri address6 = new Uri("gopher://example.contoso.com/"); + // + Uri address6 = new("gopher://example.contoso.com/"); if (address6.Scheme == Uri.UriSchemeGopher) Console.WriteLine("Uri is Gopher protocol"); - // + // - // - Uri address7 = new Uri("ftp://contoso/files/testfile.txt"); + // + Uri address7 = new("ftp://contoso/files/testfile.txt"); if (address7.Scheme == Uri.UriSchemeFtp) Console.WriteLine("Uri is Ftp protocol"); - // + // - // - Uri address8 = new Uri("https://example.contoso.com"); + // + Uri address8 = new("https://example.contoso.com"); if (address8.Scheme == Uri.UriSchemeHttps) Console.WriteLine("Uri is Https protocol."); - // + // - // + // string address = "www.contoso.com"; - string uriString = String.Format("{0}{1}{2}/", Uri.UriSchemeHttp, Uri.SchemeDelimiter, address); - #if OLDMETHOD + string uriString = $"{Uri.UriSchemeHttp}{Uri.SchemeDelimiter}{address}/"; +#if OLDMETHOD Uri result; if (Uri.TryParse(uriString, false, false, out result)) Console.WriteLine("{0} is a valid Uri", result.ToString()); else Console.WriteLine("Uri not created"); #endif - Uri result = new Uri(uriString); + Uri result = new(uriString); if (result.IsWellFormedOriginalString()) - Console.WriteLine("{0} is a well formed Uri", uriString); + Console.WriteLine($"{uriString} is a well formed Uri"); else - Console.WriteLine("{0} is not a well formed Uri", uriString); - // + Console.WriteLine($"{uriString} is not a well formed Uri"); + // } private static void SampleUserInfo() { - // - Uri uriAddress = new Uri ("http://user:password@www.contoso.com/index.htm "); + // + Uri uriAddress = new("http://user:password@www.contoso.com/index.htm "); Console.WriteLine(uriAddress.UserInfo); - Console.WriteLine("Fully Escaped {0}", uriAddress.UserEscaped ? "yes" : "no"); - // + Console.WriteLine($"Fully Escaped {(uriAddress.UserEscaped ? "yes" : "no")}"); + // } private static void UnescapeUriWithPlusConversion() { - // - String DataString = Uri.UnescapeDataString(".NET+Framework"); - Console.WriteLine("Unescaped string: {0}", DataString); + // + string DataString = Uri.UnescapeDataString(".NET+Framework"); + Console.WriteLine($"Unescaped string: {DataString}"); - String PlusString = DataString.Replace('+',' '); - Console.WriteLine("plus to space string: {0}", PlusString); - // + string PlusString = DataString.Replace('+', ' '); + Console.WriteLine($"plus to space string: {PlusString}"); + // } } } diff --git a/snippets/csharp/System/Uri/Host/source.cs b/snippets/csharp/System/Uri/Host/source.cs index 9b9051d84a3..ba1d4c4beeb 100644 --- a/snippets/csharp/System/Uri/Host/source.cs +++ b/snippets/csharp/System/Uri/Host/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,10 +8,10 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com:8080/"); - Uri myUri = new Uri(baseUri, "shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com:8080/"); + Uri myUri = new(baseUri, "shownew.htm?date=today"); Console.WriteLine(myUri.Host); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/HostComparison/source.cs b/snippets/csharp/System/Uri/HostComparison/source.cs index c8ebf4678ec..90e74411d51 100644 --- a/snippets/csharp/System/Uri/HostComparison/source.cs +++ b/snippets/csharp/System/Uri/HostComparison/source.cs @@ -1,4 +1,4 @@ -using System; +using System; public class UriHostComparison { @@ -9,7 +9,7 @@ public static void Main() // Example 1: Regular hostname (ASCII). Console.WriteLine("Example 1: Regular ASCII hostname"); - Uri uri1 = new Uri("http://www.contoso.com:8080/path"); + Uri uri1 = new("http://www.contoso.com:8080/path"); Console.WriteLine($" Host: {uri1.Host}"); // www.contoso.com Console.WriteLine($" IdnHost: {uri1.IdnHost}"); // www.contoso.com Console.WriteLine($" DnsSafeHost: {uri1.DnsSafeHost}"); // www.contoso.com @@ -17,7 +17,7 @@ public static void Main() // Example 2: International domain name (non-ASCII). Console.WriteLine("Example 2: International domain name"); - Uri uri2 = new Uri("http://münchen.de/path"); + Uri uri2 = new("http://münchen.de/path"); Console.WriteLine($" Host: {uri2.Host}"); // münchen.de (original) Console.WriteLine($" IdnHost: {uri2.IdnHost}"); // xn--mnchen-3ya.de (punycode) Console.WriteLine($" DnsSafeHost: {uri2.DnsSafeHost}"); // münchen.de or xn--mnchen-3ya.de, depending on configuration. @@ -25,7 +25,7 @@ public static void Main() // Example 3: International domain name already in punycode (encoded) form. Console.WriteLine("Example 3: Already-encoded international domain name"); - Uri uri2Encoded = new Uri("http://xn--mnchen-3ya.de/path"); + Uri uri2Encoded = new("http://xn--mnchen-3ya.de/path"); Console.WriteLine($" Host: {uri2Encoded.Host}"); // xn--mnchen-3ya.de (as provided) Console.WriteLine($" IdnHost: {uri2Encoded.IdnHost}"); // xn--mnchen-3ya.de (already punycode) Console.WriteLine($" DnsSafeHost: {uri2Encoded.DnsSafeHost}"); // xn--mnchen-3ya.de @@ -33,7 +33,7 @@ public static void Main() // Example 4: IPv6 address without zone ID. Console.WriteLine("Example 4: IPv6 address without zone ID"); - Uri uri3 = new Uri("http://[::1]:8080/path"); + Uri uri3 = new("http://[::1]:8080/path"); Console.WriteLine($" Host: {uri3.Host}"); // [::1] (with brackets) Console.WriteLine($" IdnHost: {uri3.IdnHost}"); // ::1 (without brackets) Console.WriteLine($" DnsSafeHost: {uri3.DnsSafeHost}"); // ::1 (without brackets) @@ -41,7 +41,7 @@ public static void Main() // Example 5: IPv6 link-local address with zone ID. Console.WriteLine("Example 5: IPv6 link-local address with zone ID"); - Uri uri4 = new Uri("http://[fe80::1%10]:8080/path"); + Uri uri4 = new("http://[fe80::1%10]:8080/path"); Console.WriteLine($" Host: {uri4.Host}"); // [fe80::1] (with brackets, no zone ID) Console.WriteLine($" IdnHost: {uri4.IdnHost}"); // fe80::1%10 (without brackets, with zone ID) Console.WriteLine($" DnsSafeHost: {uri4.DnsSafeHost}"); // fe80::1%10 (without brackets, with zone ID) @@ -49,7 +49,7 @@ public static void Main() // Example 6: IPv4 address. Console.WriteLine("Example 6: IPv4 address"); - Uri uri5 = new Uri("http://192.168.1.1:8080/path"); + Uri uri5 = new("http://192.168.1.1:8080/path"); Console.WriteLine($" Host: {uri5.Host}"); // 192.168.1.1 Console.WriteLine($" IdnHost: {uri5.IdnHost}"); // 192.168.1.1 Console.WriteLine($" DnsSafeHost: {uri5.DnsSafeHost}"); // 192.168.1.1 diff --git a/snippets/csharp/System/Uri/Overview/source.cs b/snippets/csharp/System/Uri/Overview/source.cs index cdcd2d216b8..e91b21816db 100644 --- a/snippets/csharp/System/Uri/Overview/source.cs +++ b/snippets/csharp/System/Uri/Overview/source.cs @@ -1,69 +1,67 @@ -using System; -using System.Net; +using System; using System.Net.Http; - public class Form1 { - protected void Method() - { - // - Uri siteUri = new Uri("http://www.contoso.com/"); + protected void Method() + { + // + Uri siteUri = new("http://www.contoso.com/"); + + // HttpClient lifecycle management best practices: + // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use + using HttpClient client = new(); + using HttpRequestMessage request = new(HttpMethod.Get, siteUri); + using HttpResponseMessage response = client.Send(request); + // + + // + Uri uri = new("https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName"); + + Console.WriteLine($"AbsolutePath: {uri.AbsolutePath}"); + Console.WriteLine($"AbsoluteUri: {uri.AbsoluteUri}"); + Console.WriteLine($"DnsSafeHost: {uri.DnsSafeHost}"); + Console.WriteLine($"Fragment: {uri.Fragment}"); + Console.WriteLine($"Host: {uri.Host}"); + Console.WriteLine($"HostNameType: {uri.HostNameType}"); + Console.WriteLine($"IdnHost: {uri.IdnHost}"); + Console.WriteLine($"IsAbsoluteUri: {uri.IsAbsoluteUri}"); + Console.WriteLine($"IsDefaultPort: {uri.IsDefaultPort}"); + Console.WriteLine($"IsFile: {uri.IsFile}"); + Console.WriteLine($"IsLoopback: {uri.IsLoopback}"); + Console.WriteLine($"IsUnc: {uri.IsUnc}"); + Console.WriteLine($"LocalPath: {uri.LocalPath}"); + Console.WriteLine($"OriginalString: {uri.OriginalString}"); + Console.WriteLine($"PathAndQuery: {uri.PathAndQuery}"); + Console.WriteLine($"Port: {uri.Port}"); + Console.WriteLine($"Query: {uri.Query}"); + Console.WriteLine($"Scheme: {uri.Scheme}"); + Console.WriteLine($"Segments: {string.Join(", ", uri.Segments)}"); + Console.WriteLine($"UserEscaped: {uri.UserEscaped}"); + Console.WriteLine($"UserInfo: {uri.UserInfo}"); - // HttpClient lifecycle management best practices: - // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use - HttpClient client = new HttpClient(); - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, siteUri); - HttpResponseMessage response = client.Send(request); - // - - // - Uri uri = new Uri("https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName"); - - Console.WriteLine($"AbsolutePath: {uri.AbsolutePath}"); - Console.WriteLine($"AbsoluteUri: {uri.AbsoluteUri}"); - Console.WriteLine($"DnsSafeHost: {uri.DnsSafeHost}"); - Console.WriteLine($"Fragment: {uri.Fragment}"); - Console.WriteLine($"Host: {uri.Host}"); - Console.WriteLine($"HostNameType: {uri.HostNameType}"); - Console.WriteLine($"IdnHost: {uri.IdnHost}"); - Console.WriteLine($"IsAbsoluteUri: {uri.IsAbsoluteUri}"); - Console.WriteLine($"IsDefaultPort: {uri.IsDefaultPort}"); - Console.WriteLine($"IsFile: {uri.IsFile}"); - Console.WriteLine($"IsLoopback: {uri.IsLoopback}"); - Console.WriteLine($"IsUnc: {uri.IsUnc}"); - Console.WriteLine($"LocalPath: {uri.LocalPath}"); - Console.WriteLine($"OriginalString: {uri.OriginalString}"); - Console.WriteLine($"PathAndQuery: {uri.PathAndQuery}"); - Console.WriteLine($"Port: {uri.Port}"); - Console.WriteLine($"Query: {uri.Query}"); - Console.WriteLine($"Scheme: {uri.Scheme}"); - Console.WriteLine($"Segments: {string.Join(", ", uri.Segments)}"); - Console.WriteLine($"UserEscaped: {uri.UserEscaped}"); - Console.WriteLine($"UserInfo: {uri.UserInfo}"); - - // AbsolutePath: /Home/Index.htm - // AbsoluteUri: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName - // DnsSafeHost: www.contoso.com - // Fragment: #FragmentName - // Host: www.contoso.com - // HostNameType: Dns - // IdnHost: www.contoso.com - // IsAbsoluteUri: True - // IsDefaultPort: False - // IsFile: False - // IsLoopback: False - // IsUnc: False - // LocalPath: /Home/Index.htm - // OriginalString: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName - // PathAndQuery: /Home/Index.htm?q1=v1&q2=v2 - // Port: 80 - // Query: ?q1=v1&q2=v2 - // Scheme: https - // Segments: /, Home/, Index.htm - // UserEscaped: False - // UserInfo: user:password + // AbsolutePath: /Home/Index.htm + // AbsoluteUri: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName + // DnsSafeHost: www.contoso.com + // Fragment: #FragmentName + // Host: www.contoso.com + // HostNameType: Dns + // IdnHost: www.contoso.com + // IsAbsoluteUri: True + // IsDefaultPort: False + // IsFile: False + // IsLoopback: False + // IsUnc: False + // LocalPath: /Home/Index.htm + // OriginalString: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName + // PathAndQuery: /Home/Index.htm?q1=v1&q2=v2 + // Port: 80 + // Query: ?q1=v1&q2=v2 + // Scheme: https + // Segments: /, Home/, Index.htm + // UserEscaped: False + // UserInfo: user:password - // - } + // + } } diff --git a/snippets/csharp/System/Uri/PathAndQuery/source.cs b/snippets/csharp/System/Uri/PathAndQuery/source.cs index 8337964ac6a..bdfaa3c7b6b 100644 --- a/snippets/csharp/System/Uri/PathAndQuery/source.cs +++ b/snippets/csharp/System/Uri/PathAndQuery/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,8 +8,8 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.PathAndQuery); // @@ -19,10 +19,10 @@ public void Method2() { // - Uri baseUri = new Uri ("http://www.contoso.com/"); - Uri myUri = new Uri (baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); - Console.WriteLine (myUri.Query); + Console.WriteLine(myUri.Query); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/Port/source.cs b/snippets/csharp/System/Uri/Port/source.cs index 77687e3cffc..6814c27f16b 100644 --- a/snippets/csharp/System/Uri/Port/source.cs +++ b/snippets/csharp/System/Uri/Port/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,11 +8,11 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri,"catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.Port); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/Scheme/source.cs b/snippets/csharp/System/Uri/Scheme/source.cs index 59ca2860b89..b3b8b29ff42 100644 --- a/snippets/csharp/System/Uri/Scheme/source.cs +++ b/snippets/csharp/System/Uri/Scheme/source.cs @@ -1,14 +1,14 @@ using System; -using System.Data; -using System.Security.Principal; + + public class Form1 { protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.Scheme); // diff --git a/snippets/csharp/System/UriBuilder/.ctor/Project.csproj b/snippets/csharp/System/UriBuilder/.ctor/Project.csproj new file mode 100644 index 00000000000..b62ae7deede --- /dev/null +++ b/snippets/csharp/System/UriBuilder/.ctor/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net10.0-windows + true + + + diff --git a/snippets/csharp/System/UriBuilder/.ctor/source.cs b/snippets/csharp/System/UriBuilder/.ctor/source.cs index 24d8691fc4f..b4906bea741 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com"); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com"); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/.ctor/source1.cs b/snippets/csharp/System/UriBuilder/.ctor/source1.cs index 311930fe00e..c1ab40bcede 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source1.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source1.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm1 : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com",8080); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com", 8080); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/.ctor/source2.cs b/snippets/csharp/System/UriBuilder/.ctor/source2.cs index 84b8d2283e1..8e9009a8caf 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source2.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source2.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm2 : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com",8080,"index.htm"); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com", 8080, "index.htm"); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/.ctor/source3.cs b/snippets/csharp/System/UriBuilder/.ctor/source3.cs index ba5a17a2204..2ec8799f768 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source3.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source3.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm3 : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com",8080,"index.htm","#top"); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com", 8080, "index.htm", "#top"); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/Fragment/source.cs b/snippets/csharp/System/UriBuilder/Fragment/source.cs index 64ff7df4ed5..0064d4c1d1c 100644 --- a/snippets/csharp/System/UriBuilder/Fragment/source.cs +++ b/snippets/csharp/System/UriBuilder/Fragment/source.cs @@ -1,19 +1,21 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 { - protected void Method() - { -// -UriBuilder uBuild = new UriBuilder("http://www.contoso.com/"); -uBuild.Path = "index.htm"; -uBuild.Fragment = "main"; + protected void Method() + { + // + UriBuilder uBuild = new("http://www.contoso.com/") + { + Path = "index.htm", + Fragment = "main" + }; -Uri myUri = uBuild.Uri; + Uri myUri = uBuild.Uri; -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/Query/main.cs b/snippets/csharp/System/UriBuilder/Query/main.cs index f4971e6c279..bdc64dd4445 100644 --- a/snippets/csharp/System/UriBuilder/Query/main.cs +++ b/snippets/csharp/System/UriBuilder/Query/main.cs @@ -1,28 +1,28 @@ #region Using directives using System; -using System.Collections.Generic; -using System.Text; + + #endregion namespace ConsoleApplication1 { - class Program - { - static void Main(string[] args) - { - // - UriBuilder baseUri = new UriBuilder("http://www.contoso.com/default.aspx?Param1=7890"); - string queryToAppend = "param2=1234"; + class Program + { + static void Main(string[] args) + { + // + UriBuilder baseUri = new("http://www.contoso.com/default.aspx?Param1=7890"); + string queryToAppend = "param2=1234"; - if (baseUri.Query != null && baseUri.Query.Length > 1) - // Note: In .NET Core and .NET 5+, you can simplify by removing - // the call to Substring(), which removes the leading "?" character. - baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; - else - baseUri.Query = queryToAppend; - // - } - } + if (baseUri.Query != null && baseUri.Query.Length > 1) + // Note: In .NET Core and .NET 5+, you can simplify by removing + // the call to Substring(), which removes the leading "?" character. + baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; + else + baseUri.Query = queryToAppend; + // + } + } } diff --git a/snippets/csharp/System/ValueType/Equals/Project.csproj b/snippets/csharp/System/ValueType/Equals/Project.csproj new file mode 100644 index 00000000000..dfdef3fd2a7 --- /dev/null +++ b/snippets/csharp/System/ValueType/Equals/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/csharp/System/ValueType/Equals/source.cs b/snippets/csharp/System/ValueType/Equals/source.cs index 4b2be270f81..eb88125f284 100644 --- a/snippets/csharp/System/ValueType/Equals/source.cs +++ b/snippets/csharp/System/ValueType/Equals/source.cs @@ -1,26 +1,27 @@ -using System; + namespace Snippets { - // - public struct Complex - { - public double m_Re; - public double m_Im; + // + public struct Complex + { + public double m_Re; + public double m_Im; - public override bool Equals( object ob ){ - if( ob is Complex ) { - Complex c = (Complex) ob; - return m_Re==c.m_Re && m_Im==c.m_Im; - } - else { - return false; - } - } + public override bool Equals(object ob) + { + if (ob is Complex) + { + Complex c = (Complex)ob; + return m_Re == c.m_Re && m_Im == c.m_Im; + } + else + { + return false; + } + } - public override int GetHashCode(){ - return m_Re.GetHashCode() ^ m_Im.GetHashCode(); - } - } - // -} \ No newline at end of file + public override int GetHashCode() => m_Re.GetHashCode() ^ m_Im.GetHashCode(); + } + // +} diff --git a/snippets/csharp/System/ValueType/Overview/example1.cs b/snippets/csharp/System/ValueType/Overview/example1.cs index c626a8da7e5..59c610aff7d 100644 --- a/snippets/csharp/System/ValueType/Overview/example1.cs +++ b/snippets/csharp/System/ValueType/Overview/example1.cs @@ -4,92 +4,90 @@ public class Utility { - public enum NumericRelationship { - GreaterThan = 1, - EqualTo = 0, - LessThan = -1 - }; - - public static NumericRelationship Compare(ValueType value1, ValueType value2) - { - if (!IsNumeric(value1)) - throw new ArgumentException("value1 is not a number."); - else if (!IsNumeric(value2)) - throw new ArgumentException("value2 is not a number."); + public enum NumericRelationship + { + GreaterThan = 1, + EqualTo = 0, + LessThan = -1 + }; - // Use BigInteger as common integral type - if (IsInteger(value1) && IsInteger(value2)) { - BigInteger bigint1 = (BigInteger) value1; - BigInteger bigint2 = (BigInteger) value2; - return (NumericRelationship) BigInteger.Compare(bigint1, bigint2); - } - // At least one value is floating point; use Double. - else { - Double dbl1 = 0; - Double dbl2 = 0; - try { - dbl1 = Convert.ToDouble(value1); - } - catch (OverflowException) { - Console.WriteLine("value1 is outside the range of a Double."); - } - try { - dbl2 = Convert.ToDouble(value2); - } - catch (OverflowException) { - Console.WriteLine("value2 is outside the range of a Double."); - } - return (NumericRelationship) dbl1.CompareTo(dbl2); - } - } - - public static bool IsInteger(ValueType value) - { - return (value is SByte || value is Int16 || value is Int32 - || value is Int64 || value is Byte || value is UInt16 - || value is UInt32 || value is UInt64 - || value is BigInteger); - } + public static NumericRelationship Compare(ValueType value1, ValueType value2) + { + if (!IsNumeric(value1)) + throw new ArgumentException("value1 is not a number."); + else if (!IsNumeric(value2)) + throw new ArgumentException("value2 is not a number."); - public static bool IsFloat(ValueType value) - { - return (value is float || value is double || value is Decimal); - } + // Use BigInteger as common integral type + if (IsInteger(value1) && IsInteger(value2)) + { + BigInteger bigint1 = (BigInteger)value1; + BigInteger bigint2 = (BigInteger)value2; + return (NumericRelationship)BigInteger.Compare(bigint1, bigint2); + } + // At least one value is floating point; use Double. + else + { + double dbl1 = 0; + double dbl2 = 0; + try + { + dbl1 = Convert.ToDouble(value1); + } + catch (OverflowException) + { + Console.WriteLine("value1 is outside the range of a Double."); + } + try + { + dbl2 = Convert.ToDouble(value2); + } + catch (OverflowException) + { + Console.WriteLine("value2 is outside the range of a Double."); + } + return (NumericRelationship)dbl1.CompareTo(dbl2); + } + } - public static bool IsNumeric(ValueType value) - { - return (value is Byte || - value is Int16 || - value is Int32 || - value is Int64 || - value is SByte || - value is UInt16 || - value is UInt32 || - value is UInt64 || - value is BigInteger || - value is Decimal || - value is Double || - value is Single); - } + public static bool IsInteger(ValueType value) => (value is sbyte || value is short || value is int + || value is long || value is byte || value is ushort + || value is uint || value is ulong + || value is BigInteger); + + public static bool IsFloat(ValueType value) => (value is float || value is double || value is decimal); + + public static bool IsNumeric(ValueType value) => (value is byte || + value is short || + value is int || + value is long || + value is sbyte || + value is ushort || + value is uint || + value is ulong || + value is BigInteger || + value is decimal || + value is double || + value is float); } // -// +// public class Example { - public static void Main() - { - Console.WriteLine(Utility.IsNumeric(12)); - Console.WriteLine(Utility.IsNumeric(true)); - Console.WriteLine(Utility.IsNumeric('c')); - Console.WriteLine(Utility.IsNumeric(new DateTime(2012, 1, 1))); - Console.WriteLine(Utility.IsInteger(12.2)); - Console.WriteLine(Utility.IsInteger(123456789)); - Console.WriteLine(Utility.IsFloat(true)); - Console.WriteLine(Utility.IsFloat(12.2)); - Console.WriteLine(Utility.IsFloat(12)); - Console.WriteLine("{0} {1} {2}", 12.1, Utility.Compare(12.1, 12), 12); - } + public static void Main() + { + Console.WriteLine(Utility.IsNumeric(12)); + Console.WriteLine(Utility.IsNumeric(true)); + Console.WriteLine(Utility.IsNumeric('c')); + Console.WriteLine(Utility.IsNumeric(new DateTime(2012, 1, 1))); + Console.WriteLine(Utility.IsInteger(12.2)); + Console.WriteLine(Utility.IsInteger(123456789)); + Console.WriteLine(Utility.IsFloat(true)); + Console.WriteLine(Utility.IsFloat(12.2)); + Console.WriteLine(Utility.IsFloat(12)); + Console.WriteLine($"{12.1} {Utility.Compare(12.1, 12)} {12}"); + } } // The example displays the following output: // True diff --git a/snippets/csharp/System/ValueType/ToString/ToString2.cs b/snippets/csharp/System/ValueType/ToString/ToString2.cs index a1377024d90..8644062a0ed 100644 --- a/snippets/csharp/System/ValueType/ToString/ToString2.cs +++ b/snippets/csharp/System/ValueType/ToString/ToString2.cs @@ -4,32 +4,29 @@ public class Example { - public static void Main() - { - var empA = new EmployeeA{ Name = "Robert",}; - Console.WriteLine(empA.ToString()); - - var empB = new EmployeeB{ Name = "Robert",}; - Console.WriteLine(empB.ToString()); - } + public static void Main() + { + var empA = new EmployeeA { Name = "Robert", }; + Console.WriteLine(empA.ToString()); + + var empB = new EmployeeB { Name = "Robert", }; + Console.WriteLine(empB.ToString()); + } } namespace Corporate.EmployeeObjects { public struct EmployeeA { - public String Name { get; set; } + public string Name { get; set; } } - + public struct EmployeeB { - public String Name { get; set; } + public string Name { get; set; } - public override String ToString() - { - return Name; - } - } + public override string ToString() => Name; + } } // The example displays the following output: // Corporate.EmployeeObjects.EmployeeA diff --git a/snippets/csharp/System/Version/.ctor/rev.cs b/snippets/csharp/System/Version/.ctor/rev.cs index 8728a2ecb91..0c4c1da9aa5 100644 --- a/snippets/csharp/System/Version/.ctor/rev.cs +++ b/snippets/csharp/System/Version/.ctor/rev.cs @@ -3,22 +3,22 @@ // MajorRevision, and MinorRevision properties. using System; -class Sample +class Sample { - public static void Main() + public static void Main() { - string fmtStd = "Standard version:\n" + - " major.minor.build.revision = {0}.{1}.{2}.{3}"; - string fmtInt = "Interim version:\n" + - " major.minor.build.majRev/minRev = {0}.{1}.{2}.{3}/{4}"; + string fmtStd = "Standard version:\n" + + " major.minor.build.revision = {0}.{1}.{2}.{3}"; + string fmtInt = "Interim version:\n" + + " major.minor.build.majRev/minRev = {0}.{1}.{2}.{3}/{4}"; - Version std = new Version(2, 4, 1128, 2); - Version interim = new Version(2, 4, 1128, (100 << 16) + 2); + Version std = new(2, 4, 1128, 2); + Version interim = new(2, 4, 1128, (100 << 16) + 2); - Console.WriteLine(fmtStd, std.Major, std.Minor, std.Build, std.Revision); - Console.WriteLine(fmtInt, interim.Major, interim.Minor, interim.Build, - interim.MajorRevision, interim.MinorRevision); + Console.WriteLine(fmtStd, std.Major, std.Minor, std.Build, std.Revision); + Console.WriteLine(fmtInt, interim.Major, interim.Minor, interim.Build, + interim.MajorRevision, interim.MinorRevision); } } /* @@ -30,4 +30,4 @@ public static void Main() major.minor.build.majRev/minRev = 2.4.1128.100/2 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Version/Overview/GettingVersions1.cs b/snippets/csharp/System/Version/Overview/GettingVersions1.cs index 7d914d90746..d775e45659b 100644 --- a/snippets/csharp/System/Version/Overview/GettingVersions1.cs +++ b/snippets/csharp/System/Version/Overview/GettingVersions1.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection; [assembly: CLSCompliant(true)] public class Class1 diff --git a/snippets/csharp/System/Version/Overview/comparisons1.cs b/snippets/csharp/System/Version/Overview/comparisons1.cs index 67c94f8978e..31749246054 100644 --- a/snippets/csharp/System/Version/Overview/comparisons1.cs +++ b/snippets/csharp/System/Version/Overview/comparisons1.cs @@ -2,33 +2,25 @@ public class Example7 { - public static void Main() - { - CompareSimple(); - } + public static void Main() => CompareSimple(); - private static void CompareSimple() - { - // - Version v1 = new(2, 0); - Version v2 = new("2.1"); - Console.Write("Version {0} is ", v1); - switch(v1.CompareTo(v2)) - { - case 0: - Console.Write("the same as"); - break; - case 1: - Console.Write("later than"); - break; - case -1: - Console.Write("earlier than"); - break; - } - Console.WriteLine($" Version {v2}."); + private static void CompareSimple() + { + // + Version v1 = new(2, 0); + Version v2 = new("2.1"); + string relationship = v1.CompareTo(v2) switch + { + -1 => "earlier than", + 0 => "the same as", + 1 => "later than", + _ => throw new InvalidOperationException() + }; - // The example displays the following output: - // Version 2.0 is earlier than Version 2.1. - // - } + Console.WriteLine($"Version {v1} is {relationship} Version {v2}."); + + // The example displays the following output: + // Version 2.0 is earlier than Version 2.1. + // + } } diff --git a/snippets/csharp/System/Version/Overview/comparisons2.cs b/snippets/csharp/System/Version/Overview/comparisons2.cs index e4f6dc58c92..3de96a7f718 100644 --- a/snippets/csharp/System/Version/Overview/comparisons2.cs +++ b/snippets/csharp/System/Version/Overview/comparisons2.cs @@ -1,24 +1,27 @@ // using System; -enum VersionTime {Earlier = -1, Same = 0, Later = 1 }; +enum VersionTime +{ + Earlier = -1, + Same = 0, + Later = 1 +} public class Example2 { - public static void Main() - { - Version v1 = new(1, 1); - Version v1a = new("1.1.0"); - ShowRelationship(v1, v1a); - - Version v1b = new(1, 1, 0, 0); - ShowRelationship(v1b, v1a); - } + public static void Main() + { + Version v1 = new(1, 1); + Version v1a = new("1.1.0"); + ShowRelationship(v1, v1a); + + Version v1b = new(1, 1, 0, 0); + ShowRelationship(v1b, v1a); + } - private static void ShowRelationship(Version v1, Version v2) - { - Console.WriteLine($"Relationship of {v1} to {v2}: {(VersionTime) v1.CompareTo(v2)}"); - } + private static void ShowRelationship(Version v1, Version v2) => + Console.WriteLine($"Relationship of {v1} to {v2}: {(VersionTime)v1.CompareTo(v2)}"); } // The example displays the following output: diff --git a/snippets/csharp/System/Version/Overview/currentapp.cs b/snippets/csharp/System/Version/Overview/currentapp.cs index 0a932351d50..82979bf7577 100644 --- a/snippets/csharp/System/Version/Overview/currentapp.cs +++ b/snippets/csharp/System/Version/Overview/currentapp.cs @@ -4,13 +4,13 @@ public class Example4 { - public static void Main() - { - // Get the version of the executing assembly (that is, this assembly). - Assembly assem = Assembly.GetEntryAssembly(); - AssemblyName assemName = assem.GetName(); - Version ver = assemName.Version; - Console.WriteLine("Application {0}, Version {1}", assemName.Name, ver.ToString()); - } + public static void Main() + { + // Get the version of the executing assembly (that is, this assembly). + Assembly assem = Assembly.GetEntryAssembly(); + AssemblyName assemName = assem.GetName(); + Version ver = assemName.Version; + Console.WriteLine($"Application {assemName.Name}, Version {ver}"); + } } // diff --git a/snippets/csharp/System/Version/Overview/currentassem.cs b/snippets/csharp/System/Version/Overview/currentassem.cs index e83f32b25e7..11559103e42 100644 --- a/snippets/csharp/System/Version/Overview/currentassem.cs +++ b/snippets/csharp/System/Version/Overview/currentassem.cs @@ -4,13 +4,13 @@ public class Example3 { - public static void Main() - { - // Get the version of the current assembly. - Assembly assem = typeof(Example3).Assembly; - AssemblyName assemName = assem.GetName(); - Version ver = assemName.Version; - Console.WriteLine("{0}, Version {1}", assemName.Name, ver.ToString()); - } + public static void Main() + { + // Get the version of the current assembly. + Assembly assem = typeof(Example3).Assembly; + AssemblyName assemName = assem.GetName(); + Version ver = assemName.Version; + Console.WriteLine($"{assemName.Name}, Version {ver}"); + } } // diff --git a/snippets/csharp/System/Version/Overview/example1.cs b/snippets/csharp/System/Version/Overview/example1.cs index e595209c12f..5fc37e45c07 100644 --- a/snippets/csharp/System/Version/Overview/example1.cs +++ b/snippets/csharp/System/Version/Overview/example1.cs @@ -2,19 +2,18 @@ using System; using System.Reflection; -[assembly:AssemblyVersionAttribute("2.0.1")] +[assembly: AssemblyVersion("2.0.1")] public class Example1 { - public static void Main() - { - Assembly thisAssem = typeof(Example1).Assembly; - AssemblyName thisAssemName = thisAssem.GetName(); - - Version ver = thisAssemName.Version; - - Console.WriteLine("This is version {0} of {1}.", ver, thisAssemName.Name); - } + public static void Main() + { + Assembly thisAssem = typeof(Example1).Assembly; + AssemblyName thisAssemName = thisAssem.GetName(); + Version ver = thisAssemName.Version; + + Console.WriteLine($"This is version {ver} of {thisAssemName.Name}."); + } } // The example displays the following output: diff --git a/snippets/csharp/System/Version/Parse/parse1.cs b/snippets/csharp/System/Version/Parse/parse1.cs index 3faf054b2c8..8fe2308e930 100644 --- a/snippets/csharp/System/Version/Parse/parse1.cs +++ b/snippets/csharp/System/Version/Parse/parse1.cs @@ -3,56 +3,63 @@ public class Example { - public static void Main() - { - string input = "4.0"; - ParseVersion(input); - - input = "4.0."; - ParseVersion(input); - - input = "1.1.2"; - ParseVersion(input); - - input = "1.1.2.01702"; - ParseVersion(input); - - input = "1.1.2.0702.119"; - ParseVersion(input); - - input = "1.3.5.2150000000"; - ParseVersion(input); - } - - private static void ParseVersion(string input) - { - try { - Version ver = Version.Parse(input); - Console.WriteLine("Converted '{0} to {1}.", input, ver); - } - catch (ArgumentNullException) { - Console.WriteLine("Error: String to be parsed is null."); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("Error: Negative value in '{0}'.", input); - } - catch (ArgumentException) { - Console.WriteLine("Error: Bad number of components in '{0}'.", - input); - } - catch (FormatException) { - Console.WriteLine("Error: Non-integer value in '{0}'.", input); - } - catch (OverflowException) { - Console.WriteLine("Error: Number out of range in '{0}'.", input); - } - } + public static void Main() + { + string input = "4.0"; + ParseVersion(input); + + input = "4.0."; + ParseVersion(input); + + input = "1.1.2"; + ParseVersion(input); + + input = "1.1.2.01702"; + ParseVersion(input); + + input = "1.1.2.0702.119"; + ParseVersion(input); + + input = "1.3.5.2150000000"; + ParseVersion(input); + } + + private static void ParseVersion(string input) + { + try + { + Version ver = Version.Parse(input); + Console.WriteLine($"Converted '{input}' to {ver}."); + } + catch (ArgumentNullException) + { + Console.WriteLine("Error: String to be parsed is null."); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"Error: Negative value in '{input}'."); + } + catch (ArgumentException) + { + Console.WriteLine($"Error: Bad number of components in '{input}'."); + } + catch (FormatException) + { + Console.WriteLine($"Error: Non-integer value in '{input}'."); + } + catch (OverflowException) + { + Console.WriteLine($"Error: Number out of range in '{input}'."); + } + } } + // The example displays the following output: -// Converted '4.0 to 4.0. +// Converted '4.0' to 4.0. // Error: Non-integer value in '4.0.'. -// Converted '1.1.2 to 1.1.2. -// Converted '1.1.2.01702 to 1.1.2.1702. +// Converted '1.1.2' to 1.1.2. +// Converted '1.1.2.01702' to 1.1.2.1702. // Error: Bad number of components in '1.1.2.0702.119'. // Error: Number out of range in '1.3.5.2150000000'. -// \ No newline at end of file + +// diff --git a/snippets/csharp/System/Version/TryParse/tryparse1.cs b/snippets/csharp/System/Version/TryParse/tryparse1.cs index e814d444c22..988e365c56b 100644 --- a/snippets/csharp/System/Version/TryParse/tryparse1.cs +++ b/snippets/csharp/System/Version/TryParse/tryparse1.cs @@ -3,42 +3,43 @@ public class Example { - public static void Main() - { - string input = "4.0"; - ParseVersion(input); - - input = "4.0."; - ParseVersion(input); - - input = "1.1.2"; - ParseVersion(input); - - input = "1.1.2.01702"; - ParseVersion(input); - - input = "1.1.2.0702.119"; - ParseVersion(input); - - input = "1.3.5.2150000000"; - ParseVersion(input); - } - - private static void ParseVersion(string input) - { - Version ver = null; - if (Version.TryParse(input, out ver)) - Console.WriteLine("Converted '{0} to {1}.", input, ver); - else - Console.WriteLine("Unable to determine the version from '{0}'.", - input); - } + public static void Main() + { + string input = "4.0"; + ParseVersion(input); + + input = "4.0."; + ParseVersion(input); + + input = "1.1.2"; + ParseVersion(input); + + input = "1.1.2.01702"; + ParseVersion(input); + + input = "1.1.2.0702.119"; + ParseVersion(input); + + input = "1.3.5.2150000000"; + ParseVersion(input); + } + + private static void ParseVersion(string input) + { + Version ver = null; + if (Version.TryParse(input, out ver)) + Console.WriteLine($"Converted '{input}' to {ver}."); + else + Console.WriteLine($"Unable to determine the version from '{input}'."); + } } + // The example displays the following output: -// Converted '4.0 to 4.0. +// Converted '4.0' to 4.0. // Unable to determine the version from '4.0.'. -// Converted '1.1.2 to 1.1.2. -// Converted '1.1.2.01702 to 1.1.2.1702. +// Converted '1.1.2' to 1.1.2. +// Converted '1.1.2.01702' to 1.1.2.1702. // Unable to determine the version from '1.1.2.0702.119'. // Unable to determine the version from '1.3.5.2150000000'. -// \ No newline at end of file + +// diff --git a/snippets/csharp/System/WeakReference/Overview/program.cs b/snippets/csharp/System/WeakReference/Overview/program.cs index e4d13b0f6e1..c8c7c2dab7a 100644 --- a/snippets/csharp/System/WeakReference/Overview/program.cs +++ b/snippets/csharp/System/WeakReference/Overview/program.cs @@ -8,21 +8,22 @@ public static void Main() { // Create the cache. int cacheSize = 50; - Random r = new Random(); - Cache c = new Cache(cacheSize); + Random r = new(); + Cache c = new(cacheSize); string DataName = ""; GC.Collect(0); // Randomly access objects in the cache. - for (int i = 0; i < c.Count; i++) { + for (int i = 0; i < c.Count; i++) + { int index = r.Next(c.Count); // Access the object by getting a property value. DataName = c[index].Name; } // Show results. - double regenPercent = c.RegenerationCount/(double)c.Count; + double regenPercent = c.RegenerationCount / (double)c.Count; Console.WriteLine($"Cache size: {c.Count}, Regenerated: {regenPercent:P0}"); } } @@ -37,49 +38,47 @@ public class Cache public Cache(int count) { - _cache = new Dictionary(); + _cache = new(); // // Add objects with a short weak reference to the cache. - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { _cache.Add(i, new WeakReference(new Data(i), false)); } // } // Number of items in the cache. - public int Count - { - get { return _cache.Count; } - } + public int Count => _cache.Count; // Number of times an object needs to be regenerated. - public int RegenerationCount - { - get { return regenCount; } - } + public int RegenerationCount => regenCount; // Retrieve a data object from the cache. public Data this[int index] { - get { + get + { // Data d = _cache[index].Target as Data; - if (d == null) { + if (d == null) + { // If the object was reclaimed, generate a new one. - Console.WriteLine("Regenerate object at {0}: Yes", index); - d = new Data(index); + Console.WriteLine($"Regenerate object at {index}: Yes"); + d = new(index); _cache[index].Target = d; regenCount++; } - else { + else + { // Object was obtained with the weak reference. - Console.WriteLine("Regenerate object at {0}: No", index); + Console.WriteLine($"Regenerate object at {index}: No"); } return d; - // - } + // + } } } @@ -96,10 +95,7 @@ public Data(int size) } // Simple property. - public string Name - { - get { return _name; } - } + public string Name => _name; } // Example of the last lines of the output: // @@ -114,4 +110,4 @@ public string Name // Regenerate object at 43: Yes // Regenerate object at 38: No // Cache size: 50, Regenerated: 94% -// \ No newline at end of file +//