diff --git a/S7.Net/Types/S7String.cs b/S7.Net/Types/S7String.cs
index 671c8e6..8e67db6 100644
--- a/S7.Net/Types/S7String.cs
+++ b/S7.Net/Types/S7String.cs
@@ -8,11 +8,18 @@ namespace S7.Net.Types
/// An S7 String has a preceeding 2 byte header containing its capacity and length
///
public static class S7String
- {
- ///
- /// The Encoding used when serializing and deserializing S7String (Encoding.ASCII by default)
- ///
- public static Encoding StringEncoding { get; set; }
+ {
+ private static Encoding stringEncoding;
+
+ ///
+ /// The Encoding used when serializing and deserializing S7String (Encoding.ASCII by default)
+ ///
+ /// StringEncoding must not be null
+ public static Encoding StringEncoding
+ {
+ get => stringEncoding ??= Encoding.ASCII;
+ set => stringEncoding = value ?? throw new ArgumentNullException(nameof(StringEncoding));
+ }
///
/// Converts S7 bytes to a string
@@ -35,7 +42,6 @@ namespace S7.Net.Types
try
{
- if (StringEncoding == null) StringEncoding = Encoding.ASCII;
return StringEncoding.GetString(bytes, 2, length);
}
catch (Exception e)
@@ -59,9 +65,8 @@ namespace S7.Net.Types
throw new ArgumentNullException(nameof(value));
}
- if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254.");
-
- if (StringEncoding == null) StringEncoding = Encoding.ASCII;
+ if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254.");
+
var bytes = StringEncoding.GetBytes(value);
if (bytes.Length > reservedLength) throw new ArgumentException($"The provided string length ({bytes.Length} is larger than the specified reserved length ({reservedLength}).");
@@ -71,13 +76,5 @@ namespace S7.Net.Types
buffer[1] = (byte)bytes.Length;
return buffer;
}
-
- ///
- /// Initializes default static properties
- ///
- static S7String()
- {
- StringEncoding = Encoding.ASCII;
- }
}
}