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):
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
1 2 3 4 5 6 |
public bool HasValue(string value, out string errorMessage) { errorMessage = default; // Some code. } |
optional parameter – default value declaring
1 2 3 4 5 |
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultVaule = default) { // Some code. } |
method call argument
1 2 3 4 5 6 |
public IEnumerable<Book> GetAllInStockBooks() => GetBooksAvailableForDisplay(default); public IEnumerable<Book> GetBooksAvailableForDisplay(Func<Book, bool> validate) { // Some code. } |
return statement
1 2 3 4 5 6 7 8 9 10 11 |
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:
- variable initialisation & assignment (errorMessage = default(string) )
- optional parameter – default value declaring (TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultVaule = default(TValue)))
- method call argument (GetBooksAvailableForDisplay(default(Func<Book, bool>)))
- return statement (return default(T))
in the below sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
/// <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:
- variable initialisation & assignment (errorMessage = default )
- optional parameter – default value declaring (TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultVaule = default))
- method call argument (GetBooksAvailableForDisplay(default))
- return statement (return default)
in the below sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
/// <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 !!!