Helper methods I like to use in C#/Unity

5 simple methods that I frequently use in almost all of my projects

I thought I'd quickly share the common methods I use and will pull into all of my projects.

ToModel()

The first is to do with serialization and you can use this for any of your desired serialization whether it be JSON or XML or something else. In my example, I'll use XML. Here the ToModel() method can be used on any string and will attempt to convert that string from XML to a class object mapping properties. I'll show an example of how to use this method after the second helper method.

public static T ToModel<T>(this string xml) where T : class
{
    if (string.IsNullOrEmpty(xml))
        return default;

    try
    {
        using (var stringReader = new StringReader(xml))
        {
            var serializer = new XmlSerializer(typeof(T));
            return serializer.Deserialize(stringReader) as T;
        }
    }
    catch (Exception ex)
    {
        LogException(ex);
        return default;
    }
}

ToXMLString()

This is the other serialization method I use and is the opposite of the ToModel() method. This will convert any object into a formatted XML string, which is handy for POSTing data to a server or saving it to a file.

public static string ToXmlString(this object obj)
{
    if (obj == null)
        return default;

    try
    {
        using (var stringWriter = new StringWriter())
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(stringWriter, obj);
            return stringWriter.ToString();
        }
    }
    catch (Exception ex)
    {
        LogException(ex);
        return default;
    }
}

Serialization example

Here is a standard example of using both methods above.

// Read the XML from a file into a string.
string xml = File.ReadAllText(fileLocation);

// Here we convert the string XML to the class object.
CustomXMLClass customClass = xml.ToModel<CustomXMLClass>();

// Do modifications to the class object here...

// Here we convert the class object to a string for file writing.
string xmlModified = customClass.ToXmlString();
File.WriteAllText(fileLocation, xmlModified);

Truncate()

This method is simple but rather useful. It truncates the string if it is too long with a desired suffix and max length. This is super useful for UI where there is limited space.

public static string Truncate(this string value, int maxLength, string truncationSuffix = "...")
{
    if (maxLength <= 0 || string.IsNullOrEmpty(value))
        return value;
    return value.Length > maxLength ? $"{value.Substring(0, maxLength)}{truncationSuffix}" : value;
}

// Usage:
string message = "This message is too long";
message = message.Truncate(20);
// Result is "This message is too ..."

ToInt()

ToInt() is pretty self-explanatory but should only be used if you can handle a default value for your output. It attempts to convert a string to an int using a default value if it fails.

public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out int result) ? result : defaultValue;

AsIEnumerator()

This is a method I use in Unity. It converts a Task to IEnumerator so you can yield on a Task within a coroutine. This is handy when using APIs that have some methods that are only asynchronous and you want to use them within a coroutine.

public static IEnumerator AsIEnumerator(this Task task)
{
    while (!task.IsCompleted)
        yield return null;

    if (task.IsFaulted)
    {
        string message = task.Exception.Message;
        Exception inner = task.Exception.InnerException;
        while (inner != null)
        {
            message += $"\n{inner.Message}";
            inner = inner.InnerException;
        }
        Debug.LogError($"Task failed - {message}");
    }
}

// Usage:
IEnumerator SomeCoroutine()
{
    yield return AsyncMethod().AsIEnumerator();
}

I hope these methods will help you in some way, feel free to share some of the methods that you use everywhere - I'd love to see them!