{"id":108,"date":"2016-03-19T11:43:03","date_gmt":"2016-03-19T10:43:03","guid":{"rendered":"https:\/\/solidt.eu\/blog\/?p=108"},"modified":"2022-06-29T10:19:48","modified_gmt":"2022-06-29T09:19:48","slug":"c-trycast-function","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-trycast-function\/","title":{"rendered":"C# TryCast function"},"content":{"rendered":"\n<p>Update in 2022:<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">public static T GetFieldValue&lt;T>(IDictionary&lt;string, object> dict, string fieldName, T defaultValue = default)\n{\n\tif (dict.TryGetValue(fieldName, out var value))\n\t\treturn GetValueOrDefault(value, defaultValue);\n\treturn defaultValue;\n}\n\npublic static T ConvertValueOrDefault&lt;T>(object value, T def = default)\n{\n\tif (value == null) return def;\n\tif (value is T t) return t;\n\tif (typeof(T) == typeof(string)) {\n\t\treturn (T)(object)$\"{value}\";\n\t}\n\tvar basicType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);\n\ttry {\n\t\treturn (T)Convert.ChangeType(value, basicType);\n\t} catch { } \/\/ ignore value conversion error\n\treturn def;\n}<\/pre><\/div>\n\n\n\n<p>When dealing with unknown values, e.g. user input or dynamic.<br>I wrote a small function:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static T TryCast(T def, params object[] list)\n{\n\tforeach (object obj in list)\n\t{\n\t\tif (obj == null)\n\t\t\tcontinue;\n\n\t\t\/\/if (typeof(T) == typeof(string))\n\t\t\/\/{\n\t\t\/\/     if (String.IsNullOrWhiteSpace(obj.ToString()))\n\t\t\/\/     {\n\t\t\/\/         continue;\n\t\t\/\/     }\n\t\t\/\/}\n\n\t\tif (obj is T)\n\t\t\treturn (T)obj;\n\n\t\t\/\/ for converting long to int etc.\n\t\ttry\n\t\t{\n\t\t\treturn (T)Convert.ChangeType(obj, typeof(T));\n\t\t}\n\t\tcatch (Exception)\n\t\t{\n\t\t\t\/\/Ignore\n\t\t}\n\t}\n\treturn def;\n}\n<\/pre>\n\n\n\n<p>The &#8216;skip empty strings&#8217; is commented and may be used to fullfill your needs.<\/p>\n\n\n\n<p>Usage example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">if (TryCast(false, table.Row[\"Enabled\"])) {\n\n}\n<\/pre>\n\n\n\n<p>A variation of this function, used to get the correct type from a key of the Session object:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static T SessionGet(string key, T def)\n{\n\tif (HttpContext.Current != null &amp;&amp; HttpContext.Current.Session != null)\n\t{\t\t\t\t\t \n\t\tobject obj = HttpContext.Current.Session[key];\n\t\tif (obj == null)\n\t\t{\n\t\t\treturn def;\n\t\t}\n\n\t\tif (obj is T)\n\t\t{\n\t\t\treturn (T)obj;\n\t\t}\t\t\t\t\n\t}\n\treturn def;\n}\n\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Update in 2022: When dealing with unknown values, e.g. user input or dynamic.I wrote a small function: The &#8216;skip empty strings&#8217; is commented and may be used to fullfill your needs. Usage example: A variation of this function, used to get the correct type from a key of the Session object:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6],"tags":[],"class_list":["post-108","post","type-post","status-publish","format-standard","hentry","category-dotnet"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/108","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=108"}],"version-history":[{"count":9,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/108\/revisions"}],"predecessor-version":[{"id":6351,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/108\/revisions\/6351"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=108"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=108"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=108"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}