Showing posts with label Extension method. Show all posts
Showing posts with label Extension method. Show all posts

Thursday, June 3, 2021

String validation

Lately, I'm often faced to check if a given string is null, empty or only white space. You all know the built-in method string.IsNullOrEmpty(string). However when writting code, for me, it feels quite juddery to use a static type method to check that. So I decided to give an extension method so I can just write stringVariable.IsNullOrEmpty(). You may think: "How can you execute a member method on a null-reference?". This is possible, because all extended methods are technically seen, static methods - they just pretend to be member methods.

And when I do variable checks, I like to use the null-coalescing operator (the double question mark ??). However, this is not possible when the string is just empty or whitespace. To solve that, I wrote also some extended methods, so you can just use stringVariable.EmptyToNull() or stringVariable.WhiteSpaceToNull(). Both just straighten a given value to null, if it equals empty or white space.

using System;
using System.Globalization;
 
namespace Luegisdorf
{
    
/// <summary>
    
/// Provides extended functionality for instances of type string
    
/// </summary>
    
public static class StringExtensions
    {
        
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
        
public static bool IsNullOrEmpty(this string value)
            => 
string.IsNullOrEmpty(value);
 
        
/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
        
public static bool IsNullOrWhiteSpace(this string value)
            => 
string.IsNullOrWhiteSpace(value);
 
 
        
/// <summary>
        
/// Straights string to <c>null</c>, if given instance equals to empty string.
        
/// </summary>
        
/// <remarks>
        
/// Can mostly used to null-straighten a string when using validation 
        
/// with null-coalescing operator.
        
/// </remarks>
        
/// <param name="instance">
        
/// The instance to straighten
        
/// </param>
        
/// <returns>
        
/// <c>Null</c>, if the given <paramref>instance</paramref> is already <c>null</c> 
        
/// or equals empty string, 
        
/// otherwise the given <c>instance</c>.
        
/// </returns>
        
/// <example>
        
/// Inline usage: 
        
/// <code>
        
/// var candidate = string.Empty;
        
/// var length = (candidate.EmptyToNull() 
        
///     ?? throw new Exception("Candidate must contain value")).Length;
        
/// </code>        
        
/// 
        
/// If condition usage: 
        
/// <code>
        
/// var candidate = string.Empty;
        
/// if ((candidate.EmptyToNull() 
        
///     ?? throw new Exception("Candidate must contain value")) 
        
///         is string properString)
        
/// {
        
///    var length = properString.Length;
        
///    var firstCharacter = properString[0];
        
/// }
        
/// </code>        
        
/// </example>
        
public static string EmptyToNull(this string instance)
        {
            
string ret = instance;
 
            
if (string.IsNullOrEmpty(instance))
            {
                ret = 
null;
            }
            
return ret;
        }
 
        
/// <summary>
        
/// Straights string to <c>null</c>, if given instance equals to empty string.
        
/// </summary>
        
/// <remarks>
        
/// Can mostly used to null-straighten a string when using validation 
        
/// with null-coalescing operator.
        
/// </remarks>
        
/// <param name="instance">
        
/// The instance to straighten
        
/// </param>
        
/// <returns>
        
/// <c>Null</c>, if the given <paramref>instance</paramref> is already <c>null</c> 
        
/// or equals white space, 
        
/// otherwise the given <c>instance</c>.
        
/// </returns>
        
/// <example>
        
/// Inline usage: 
        
/// <code>
        
/// var candidate = string.Empty;
        
/// var length = (candidate.WhiteSpaceToNull() 
        
///     ?? throw new Exception("Candidate must contain value")).Length;
        
/// </code>        
        
/// 
        
/// If condition usage: 
        
/// <code>
        
/// var candidate = string.Empty;
        
/// if ((candidate.WhiteSpaceToNull() 
        
///     ?? throw new Exception("Candidate must contain value")) 
        
///         is string properString)
        
/// {
        
///    var length = properString.Length;
        
///    var firstCharacter = properString[0];
        
/// }
        
/// </code>        
        
/// </example>
        
public static string WhiteSpaceToNull(this string instance)
        {
            
string ret = instance;
 
            
if (string.IsNullOrWhiteSpace(instance))
            
{
                ret = 
null;
            }
            
return ret;
        }
    }
}


Thursday, May 13, 2021

Convert string to title case

There is a possibility to convert any string to title case, taking care of culture in .NET. However this functionality is quite hidden and has an exception rule for words which are written entirely in uppercase. So I decided to create some extension methods on type string for easier access an with the possibility to bypass the "only-uppercase" exception rule.

using System;
using System.Globalization;
 
namespace Luegisdorf
{
    
/// <summary>
    
/// Contains extensions for type string
    
/// </summary>
    
public static class StringExtensions
    {
        
/// <summary>
        
/// Converts the specified string to title case.
        
/// </summary>
        
/// <param name="subject">
        
/// The specified string converted to title case.
        
/// </param>
        
/// <param name="keepOnlyUppercase">
        
/// If <c>true</c>, only-uppercase <c>subject</c> 
        
/// will be retained as uppercase, otherwise only-uppercase 
        
/// <c>subject</c> will title cased as well.
        
/// </param>
        
/// <param name="cultureInfo">
        
/// The culture information used for conversion.
        
/// </param>
        
/// <returns>
        
/// The title cased <c>subject</c>
        
/// </returns>
        
public static string ToTitleCase(this string subjectbool keepOnlyUppercase
            
CultureInfo cultureInfo
        {
            
var textToConvert = subject 
                ?? 
throw new ArgumentNullException(nameof(subject));
            
var cultureInformation = cultureInfo 
                ?? 
throw new ArgumentNullException(nameof(cultureInfo));
 
            
if (!keepOnlyUppercase)
            {
                
/* since TextInfo.ToTitleCase keeps only uppercase words, 
                 * we need to ensure the subject does not contain entirely
                 * uppercase words
                 */

                textToConvert = cultureInformation.TextInfo.ToLower(textToConvert);
            }
 
            
return cultureInfo.TextInfo.ToTitleCase(textToConvert);
        }
 
        
/// <summary>
        
/// Converts the specified string to title case.
        
/// </summary>
        
/// <param name="subject">
        
/// The specified string converted to title case.
        
/// </param>
        
/// <param name="keepOnlyUppercase">
        
/// If <c>true</c>, only-uppercase <c>subject</c> 
        
/// will be retained as uppercase, otherwise only-uppercase 
        
/// <c>subject</c> will title cased as well.
        
/// </param>
        
/// <returns>
        
/// The title cased <c>subject</c>
        
/// </returns>
        
public static string ToTitleCase(this string subjectbool keepOnlyUppercase)
            => ToTitleCase(subject, keepOnlyUppercase, CultureInfo.CurrentCulture);
 
 
        
/// <summary>
        
/// Converts the specified string to title case 
        
/// (including for words that are entirely in uppercase).
        
/// </summary>
        
/// <param name="subject">
        
/// The specified string converted to title case.
        
/// </param>
        
/// <param name="cultureInfo">
        
/// The culture information used for conversion.
        
/// </param>
        
/// <returns>
        
/// The title cased <c>subject</c>
        
/// </returns>
        
public static string ToTitleCase(this string subject, CultureInfo cultureInfo)
            => ToTitleCase(subject, 
false, cultureInfo);
 
 
        
/// <summary>
        
/// Converts the specified string to title case 
        
/// (including for words that are entirely in uppercase).
        
/// </summary>
        
/// <param name="subject">
        
/// The specified string converted to title case.
        
/// </param>
        
/// <returns>
        
/// The title cased <c>subject</c>
        
/// </returns>
        
public static string ToTitleCase(this string subject)
            
=> ToTitleCase(subject, CultureInfo.CurrentCulture);
 
    }
}