How To Truncate A String Safely In C#

x.Substring(0, Math.Min(x.Length, size))

Example:

string truncatedJHAName = this.JobHazardAnalysis.Name.Substring(0, Math.Min(this.JobHazardAnalysis.Name.Length, 25));
Advertisements

.NET Version of Clone

One of my peers wrote this commenting on how much easier it was to clone in .NET vs Java.

Within your entity/object:

        public object Clone()
        {
            object clone;
            using (MemoryStream memory = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(memory, this);
                memory.Seek(0, SeekOrigin.Begin);
                clone = formater.Deserialize(memory);
                return clone;
            }
        }