C# 7.1’s default value expressions enhancement: default literal expressions

For using C# 7.1, set Language Version to “C# latest minor version(latest)” or “C# 7.1”  in C# project (Advanced Build Settings):

C# 7.1 default

default literal expressions and type inference in C# 7.1

default literal can be used when type of the expression can be inferred. It can be used in:

variable initialisation & assignment

public bool HasValue(string value, out string errorMessage)
{
	errorMessage = default;

	// Some code.
}

optional parameter – default value declaring

public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, 
	TValue defaultVaule = default)
{
	// Some code.
}

method call argument

public IEnumerable<Book> GetAllInStockBooks() => GetBooksAvailableForDisplay(default);

public IEnumerable<Book> GetBooksAvailableForDisplay(Func<Book, bool> validate)
{
	// Some code.
}

return statement

public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
{
	// Some Code.

	if (row.IsDBNull(ordinal))
	{
		return default;
	}

	// Some Code.
}

Full sample code to explain the use of default value expressions in older versions of C# (before C# 7.1)

Note the use of default value expressions:

  1. variable initialisation & assignment (errorMessage = default(string) )
  2. optional parameter – default value declaring (TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultVaule = default(TValue)))
  3. method call argument (GetBooksAvailableForDisplay(default(Func<Book, bool>)))
  4. return statement (return default(T))

in the below sample code:

/// <summary>
///     Dictionary Extentions.
/// </summary>
public static class DictionaryExtentions
{
	/// <summary>
	///     Get Value Or Default.
	/// </summary>
	/// <typeparam name="TKey">Type Param.</typeparam>
	/// <typeparam name="TValue">Type Param.</typeparam>
	/// <param name="dict">Dictionary.</param>
	/// <param name="key">Key.</param>
	/// <param name="defaultVaule">Default value to use.</param>
	/// <returns>Value.</returns>
	public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultVaule = default(TValue))
	{
		// value will be the result or the default for TValue
		TValue result;
		if (dict.TryGetValue(key, out result) == false)
		{
			result = defaultVaule;
		}

		return result;
	}
}

/// <summary>
///     DataReader Extentions.
/// </summary>
public static class DataReaderExtentions
{
	/// <summary>
	///     Get Value Or Default.
	/// </summary>
	/// <typeparam name="T">Type Param.</typeparam>
	/// <param name="row">DataReader row.</param>
	/// <param name="fieldName">Field Name.</param>
	/// <returns></returns>
	public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
	{
		int ordinal = row.GetOrdinal(fieldName);

		if (row.IsDBNull(ordinal))
		{
			return default(T);
		}

		return (T)row.GetValue(ordinal);
	}
}

/// <summary>
///     CSharp Samples.
/// </summary>
public class CSharp
{
	/// <summary>
	///     Input string has value or not.
	/// </summary>
	/// <param name="value">Input string.</param>
	/// <param name="errorMessage">Error Message (out parameter).</param>
	/// <returns>true or false.</returns>
	public bool HasValue(string value, out string errorMessage)
	{
		errorMessage = default(string);

		if (value == null)
		{
			errorMessage = $"{nameof(value)} is null.";
		}
		else if (value.Equals(string.Empty))
		{
			errorMessage = $"{nameof(value)} is empty.";
		}
		else if (value.Trim().Equals(string.Empty))
		{
			errorMessage = $"{nameof(value)} contains only whitespaces.";
		}

		return string.IsNullOrEmpty(errorMessage);
	}

	/// <summary>
	///     Get all in stock books.
	/// </summary>
	/// <returns></returns>
	public IEnumerable<Book> GetAllInStockBooks() => GetBooksAvailableForDisplay(default(Func<Book, bool>));

	/// <summary>
	///     Books available for display.
	/// </summary>
	/// <param name="validate">Validate function.</param>
	/// <returns>Valid books for display.</returns>
	public IEnumerable<Book> GetBooksAvailableForDisplay(Func<Book, bool> validate)
	{
		IEnumerable<Book> booksAvailableInStock = GetBooks().Where(x => x.InStock);

		if (validate == null)
		{
			return booksAvailableInStock;
		}

		return booksAvailableInStock.Where(x => validate(x));
	}

	/// <summary>
	///     Is valid book for display.
	/// </summary>
	/// <param name="book">Book.</param>
	/// <returns>Valid: true or false.</returns>
	public bool IsValidBookForDisplay(Book book)
	{
		if (book == null
			|| string.IsNullOrWhiteSpace(book.Publisher)
			|| string.IsNullOrWhiteSpace(book.BookCategory)
			|| string.IsNullOrWhiteSpace(book.Title)
			|| book.Id <= 0
			|| book.Price <= 0)
		{
			return false;
		}

		return true;
	}

	/// <summary>
	///     Get Books.
	/// </summary>
	private IEnumerable<Book> GetBooks() =>
		new List<Book>
		{
		   new  Book { Publisher = "", BookCategory = "Web Development", Id = 1, Price = 450, Title = "Book1", InStock = false  },
		   new  Book { Publisher = "Apress", BookCategory = "Programming", Id = 2, Price = 250, Title = "Book2", InStock = true  }, // valid
		   new  Book { Publisher = "wrox", BookCategory = "", Id = 3, Price = 499, Title = "Book3", InStock = true  },
		   new  Book { Publisher = "Apress", BookCategory = "Mobile", Id = 0, Price = 350, Title = "Book5", InStock = true  },
		   new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 6, Price = 485, Title = "Book6", InStock = false  }, // valid
		   new  Book { Publisher = "Apress", BookCategory = "C#", Id = 7, Price = 0, Title = "Book7", InStock = false  },
		   new  Book { Publisher = "Apress", BookCategory = "C#", Id = 9, Price = 500, Title = "", InStock = true  },
		};
}

/// <summary>
///  Book Model.
/// </summary>
public class Book
{
	public string Publisher { get; set; }
	public string BookCategory { get; set; }
	public int Id { get; set; }
	public string Title { get; set; }
	public decimal Price { get; set; }
	public bool InStock { get; set; }
}

Full sample code to explain the use of C# 7.1’s default literal expressions

Note the use of default literal expressions:

  1. variable initialisation & assignment (errorMessage = default )
  2. optional parameter – default value declaring (TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultVaule = default))
  3. method call argument (GetBooksAvailableForDisplay(default))
  4. return statement (return default)

in the below sample code:

/// <summary>
///     Dictionary Extentions.
/// </summary>
public static class DictionaryExtentions
{
	/// <summary>
	///     Get Value Or Default.
	/// </summary>
	/// <typeparam name="TKey">Type Param.</typeparam>
	/// <typeparam name="TValue">Type Param.</typeparam>
	/// <param name="dict">Dictionary.</param>
	/// <param name="key">Key.</param>
	/// <param name="defaultVaule">Default value to use.</param>
	/// <returns>Value.</returns>
	public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, 
		TValue defaultVaule = default)
	{
		// value will be the result or the default for TValue
		if (dict.TryGetValue(key, out TValue result) == false)
		{
			result = defaultVaule;
		}

		return result;
	}
}

/// <summary>
///     DataReader Extentions.
/// </summary>
public static class DataReaderExtentions
{
	/// <summary>
	///     Get Value Or Default.
	/// </summary>
	/// <typeparam name="T">Type Param.</typeparam>
	/// <param name="row">DataReader row.</param>
	/// <param name="fieldName">Field Name.</param>
	/// <returns></returns>
	public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
	{
		int ordinal = row.GetOrdinal(fieldName);

		if (row.IsDBNull(ordinal))
		{
			return default;
		}

		return (T)row.GetValue(ordinal);
	}
}

/// <summary>
///     CSharp7_1 Samples.
/// </summary>
public class CSharp7_1
{
	/// <summary>
	///     Input string has value or not.
	/// </summary>
	/// <param name="value">Input string.</param>
	/// <param name="errorMessage">Error Message (out parameter).</param>
	/// <returns>true or false.</returns>
	public bool HasValue(string value, out string errorMessage)
	{
		errorMessage = default;

		if (value == null)
		{
			errorMessage = $"{nameof(value)} is null.";
		}
		else if (value.Equals(string.Empty))
		{
			errorMessage = $"{nameof(value)} is empty.";
		}
		else if (value.Trim().Equals(string.Empty))
		{
			errorMessage = $"{nameof(value)} contains only whitespaces.";
		}

		return string.IsNullOrEmpty(errorMessage);
	}

	/// <summary>
	///     Get all in stock books.
	/// </summary>
	/// <returns></returns>
	public IEnumerable<Book> GetAllInStockBooks() => GetBooksAvailableForDisplay(default);

	/// <summary>
	///     Books available for display.
	/// </summary>
	/// <param name="validate">Validate function.</param>
	/// <returns>Valid books for display.</returns>
	public IEnumerable<Book> GetBooksAvailableForDisplay(Func<Book, bool> validate)
	{
		IEnumerable<Book> booksAvailableInStock = GetBooks().Where(x => x.InStock);

		if (validate == null)
		{
			return booksAvailableInStock;
		}

		return booksAvailableInStock.Where(x => validate(x));
	}

	/// <summary>
	///     Is valid book for display.
	/// </summary>
	/// <param name="book">Book.</param>
	/// <returns>Valid: true or false.</returns>
	public bool IsValidBookForDisplay(Book book)
	{
		if (book == null
			|| string.IsNullOrWhiteSpace(book.Publisher)
			|| string.IsNullOrWhiteSpace(book.BookCategory)
			|| string.IsNullOrWhiteSpace(book.Title)
			|| book.Id <= 0
			|| book.Price <= 0)
		{
			return false;
		}

		return true;
	}

	/// <summary>
	///     Get Books.
	/// </summary>
	private IEnumerable<Book> GetBooks() =>
		new List<Book>
		{
		   new  Book { Publisher = "", BookCategory = "Web Development", Id = 1, Price = 450, Title = "Book1", InStock = false  },
		   new  Book { Publisher = "Apress", BookCategory = "Programming", Id = 2, Price = 250, Title = "Book2", InStock = true  }, // valid
		   new  Book { Publisher = "wrox", BookCategory = "", Id = 3, Price = 499, Title = "Book3", InStock = true  },
		   new  Book { Publisher = "Apress", BookCategory = "Mobile", Id = 0, Price = 350, Title = "Book5", InStock = true  },
		   new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 6, Price = 485, Title = "Book6", InStock = false  }, // valid
		   new  Book { Publisher = "Apress", BookCategory = "C#", Id = 7, Price = 0, Title = "Book7", InStock = false  },
		   new  Book { Publisher = "Apress", BookCategory = "C#", Id = 9, Price = 500, Title = "", InStock = true  },
		};
}

/// <summary>
///  Book Model.
/// </summary>
public class Book
{
	public string Publisher { get; set; }
	public string BookCategory { get; set; }
	public int Id { get; set; }
	public string Title { get; set; }
	public decimal Price { get; set; }
	public bool InStock { get; set; }
}

Happy Coding !!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *