<p>Let me use the following example to explain my question:</p>
<pre class="lang-csharp prettyprint-override"><code>public string ExampleFunction(string Variable) {
    return something;
}

string WhatIsMyName = &quot;Hello World&quot;;
string Hello = ExampleFunction(WhatIsMyName);
</code></pre>
<p>When I pass the variable <code>WhatIsMyName</code> to the <code>ExampleFunction</code>, I want to be able to get a string of the <em>original</em> variable's name. Perhaps something like:</p>
<pre class="lang-csharp prettyprint-override"><code>Variable.OriginalName.ToString() // == &quot;WhatIsMyName&quot;
</code></pre>
<p>Is there any way to do this?</p>

[{'answer_id': 72139, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': -1, 'selected': True, 'text': "<p><strong>No.</strong> I don't think so.</p>\n<p>The variable name that you use is for your convenience and readability. The compiler doesn't need it &amp; just chucks it out if I'm not mistaken.</p>\n<p>If it helps, you could define a new class called <code>NamedParameter</code> with attributes <code>Name</code> and <code>Param</code>. You then pass this object around as parameters.</p>\n"}, {'answer_id': 72145, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 6, 'selected': False, 'text': "<p>What you want isn't possible directly but you can use Expressions in C# 3.0:</p>\n\n<pre><code>public void ExampleFunction(Expression&lt;Func&lt;string, string&gt;&gt; f) {\n    Console.WriteLine((f.Body as MemberExpression).Member.Name);\n}\n\nExampleFunction(x =&gt; WhatIsMyName);\n</code></pre>\n\n<p>Note that this relies on unspecified behaviour and while it does work in Microsoft’s current C# and VB compilers, <strong>and</strong> in Mono’s C# compiler, there’s no guarantee that this won’t stop working in future versions.</p>\n"}, {'answer_id': 72150, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 0, 'selected': False, 'text': '<p>The short answer is no ... unless you are really really motivated.</p>\n\n<p>The only way to do this would be via reflection and stack walking.  You would have to get a stack frame, work out whereabouts in the calling function you where invoked from and then using the CodeDOM try to find the right part of the tree to see what the expression was.</p>\n\n<p>For example, what if the invocation was ExampleFunction("a" + "b")?</p>\n'}, {'answer_id': 72155, 'author': 'rp.', 'author_id': 2536, 'author_profile': 'https://Stackoverflow.com/users/2536', 'pm_score': 0, 'selected': False, 'text': "<p>No. A reference to your string variable gets passed to the funcion--there isn't any inherent metadeta about it included. Even reflection wouldn't get you out of the woods here--working backwards from a single reference type doesn't get you enough info to do what you need to do. </p>\n\n<p>Better go back to the drawing board on this one!</p>\n\n<p>rp</p>\n"}, {'answer_id': 72186, 'author': 'Adam Vigh', 'author_id': 1613872, 'author_profile': 'https://Stackoverflow.com/users/1613872', 'pm_score': 0, 'selected': False, 'text': '<p>You could use reflection to get all the properties of an object, than loop through it, and get the value of the property where the name (of the property) matches the passed in parameter.</p>\n'}, {'answer_id': 72187, 'author': 'penderi', 'author_id': 32027, 'author_profile': 'https://Stackoverflow.com/users/32027', 'pm_score': 0, 'selected': False, 'text': "<p>Well had a bit of look. <em>of course</em> you can't use any Type information. \nAlso, the name of a local variable is not available at runtime\nbecause their names are not compiled into the assembly's metadata.</p>\n"}, {'answer_id': 72194, 'author': 'Nate Kohari', 'author_id': 1282, 'author_profile': 'https://Stackoverflow.com/users/1282', 'pm_score': 2, 'selected': False, 'text': '<p>No, but whenever you find yourself doing extremely complex things like this, you might want to re-think your solution. Remember that code should be easier to read than it was to write.</p>\n'}, {'answer_id': 72197, 'author': 'kevin42', 'author_id': 10705, 'author_profile': 'https://Stackoverflow.com/users/10705', 'pm_score': 2, 'selected': False, 'text': '<p>System.Environment.StackTrace will give you a string that includes the current call stack. You could parse that to get the information, which includes the variable names for each call. </p>\n'}, {'answer_id': 72467, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': 1, 'selected': False, 'text': '<p>Thanks for all the responses. I guess I\'ll just have to go with what I\'m doing now.</p>\n\n<p>For those who wanted to know why I asked the above question. I have the following function:</p>\n\n<pre><code>string sMessages(ArrayList aMessages, String sType) {\n    string sReturn = String.Empty;\n    if (aMessages.Count &gt; 0) {\n        sReturn += "&lt;p class=\\"" + sType + "\\"&gt;";\n        for (int i = 0; i &lt; aMessages.Count; i++) {\n            sReturn += aMessages[i] + "&lt;br /&gt;";\n        }\n        sReturn += "&lt;/p&gt;";\n    }\n    return sReturn;\n}\n</code></pre>\n\n<p>I send it an array of error messages and a css class which is then returned as a string for a webpage.</p>\n\n<p>Every time I call this function, I have to define sType. Something like:</p>\n\n<pre><code>output += sMessages(aErrors, "errors");\n</code></pre>\n\n<p>As you can see, my variables is called aErrors and my css class is called errors. I was hoping my cold could figure out what class to use based on the variable name I sent it.</p>\n\n<p>Again, thanks for all the responses.</p>\n'}, {'answer_id': 72706, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': '<p>GateKiller, what\'s wrong with my workaround? You could rewrite your function trivially to use it (I\'ve taken the liberty to improve the function on the fly):</p>\n\n<pre><code>static string sMessages(Expression&lt;Func&lt;List&lt;string&gt;&gt;&gt; aMessages) {\n    var messages = aMessages.Compile()();\n\n    if (messages.Count == 0) {\n        return "";\n    }\n\n    StringBuilder ret = new StringBuilder();\n    string sType = ((MemberExpression)aMessages.Body).Member.Name;\n\n    ret.AppendFormat("&lt;p class=\\"{0}\\"&gt;", sType);\n    foreach (string msg in messages) {\n        ret.Append(msg);\n        ret.Append("&lt;br /&gt;");\n    }\n    ret.Append("&lt;/p&gt;");\n    return ret.ToString();\n}\n</code></pre>\n\n<p>Call it like this:</p>\n\n<pre><code>var errors = new List&lt;string&gt;() { "Hi", "foo" };\nvar ret = sMessages(() =&gt; errors);\n</code></pre>\n'}, {'answer_id': 365413, 'author': 'Rinat Abdullin', 'author_id': 47366, 'author_profile': 'https://Stackoverflow.com/users/47366', 'pm_score': 5, 'selected': False, 'text': '<pre><code>static void Main(string[] args)\n{\n  Console.WriteLine("Name is \'{0}\'", GetName(new {args}));\n  Console.ReadLine();\n}\n\nstatic string GetName&lt;T&gt;(T item) where T : class\n{\n  var properties = typeof(T).GetProperties();\n  Enforce.That(properties.Length == 1);\n  return properties[0].Name;\n}\n</code></pre>\n\n<p>More details are in <a href="http://web.archive.org/web/20130124234247/http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html" rel="noreferrer">this blog post</a>.</p>\n'}, {'answer_id': 14671261, 'author': 'nawfal', 'author_id': 661933, 'author_profile': 'https://Stackoverflow.com/users/661933', 'pm_score': 4, 'selected': False, 'text': '<p>Three ways:</p>\n\n<p>1) Something without reflection at all:</p>\n\n<pre><code>GetParameterName1(new { variable });\n\npublic static string GetParameterName1&lt;T&gt;(T item) where T : class\n{\n    if (item == null)\n        return string.Empty;\n\n    return item.ToString().TrimStart(\'{\').TrimEnd(\'}\').Split(\'=\')[0].Trim();\n}\n</code></pre>\n\n<p>2) Uses reflection, but this is way faster than other two.</p>\n\n<pre><code>GetParameterName2(new { variable });\n\npublic static string GetParameterName2&lt;T&gt;(T item) where T : class\n{\n    if (item == null)\n        return string.Empty;\n\n    return typeof(T).GetProperties()[0].Name;\n}\n</code></pre>\n\n<p>3) The slowest of all, don\'t use.</p>\n\n<pre><code>GetParameterName3(() =&gt; variable);\n\npublic static string GetParameterName3&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expr)\n{\n    if (expr == null)\n        return string.Empty;\n\n    return ((MemberExpression)expr.Body).Member.Name;\n}\n</code></pre>\n\n<p>To get a combo parameter name and value, you can extend these methods. Of course its easy to get value if you pass the parameter separately as another argument, but that\'s inelegant. Instead:</p>\n\n<p>1)</p>\n\n<pre><code>public static string GetParameterInfo1&lt;T&gt;(T item) where T : class\n{\n    if (item == null)\n        return string.Empty;\n\n    var param = item.ToString().TrimStart(\'{\').TrimEnd(\'}\').Split(\'=\');\n    return "Parameter: \'" + param[0].Trim() +\n           "\' = " + param[1].Trim();\n}\n</code></pre>\n\n<p>2)</p>\n\n<pre><code>public static string GetParameterInfo2&lt;T&gt;(T item) where T : class\n{\n    if (item == null)\n        return string.Empty;\n\n    var param = typeof(T).GetProperties()[0];\n    return "Parameter: \'" + param.Name +\n           "\' = " + param.GetValue(item, null);\n}\n</code></pre>\n\n<p>3)</p>\n\n<pre><code>public static string GetParameterInfo3&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expr)\n{\n    if (expr == null)\n        return string.Empty;\n\n    var param = (MemberExpression)expr.Body;\n    return "Parameter: \'" + param.Member.Name +\n           "\' = " + ((FieldInfo)param.Member).GetValue(((ConstantExpression)param.Expression).Value);\n}\n</code></pre>\n\n<p>1 and 2 are of comparable speed now, 3 is again sluggish.</p>\n'}, {'answer_id': 19835965, 'author': 'Dipon Roy', 'author_id': 2948523, 'author_profile': 'https://Stackoverflow.com/users/2948523', 'pm_score': 2, 'selected': False, 'text': '<p>Well Try this Utility class,</p>\n\n<pre><code>public static class Utility\n{\n    public static Tuple&lt;string, TSource&gt; GetNameAndValue&lt;TSource&gt;(Expression&lt;Func&lt;TSource&gt;&gt; sourceExpression)\n    {\n        Tuple&lt;String, TSource&gt; result = null;\n        Type type = typeof (TSource);\n        Func&lt;MemberExpression, Tuple&lt;String, TSource&gt;&gt; process = delegate(MemberExpression memberExpression)\n                                                                    {\n                                                                        ConstantExpression constantExpression = (ConstantExpression)memberExpression.Expression;\n                                                                        var name = memberExpression.Member.Name;\n                                                                        var value = ((FieldInfo)memberExpression.Member).GetValue(constantExpression.Value);\n                                                                        return new Tuple&lt;string, TSource&gt;(name, (TSource) value);\n                                                                    };\n\n        Expression exception = sourceExpression.Body;\n        if (exception is MemberExpression)\n        {\n            result = process((MemberExpression)sourceExpression.Body);\n        }\n        else if (exception is UnaryExpression)\n        {\n            UnaryExpression unaryExpression = (UnaryExpression)sourceExpression.Body;\n            result = process((MemberExpression)unaryExpression.Operand);\n        }\n        else\n        {\n            throw new Exception("Expression type unknown.");\n        }\n\n        return result;\n    }\n\n\n}\n</code></pre>\n\n<p>And User It Like</p>\n\n<pre><code>    /*ToDo : Test Result*/\n    static void Main(string[] args)\n    {\n        /*Test : primivit types*/\n        long maxNumber = 123123;\n        Tuple&lt;string, long&gt; longVariable = Utility.GetNameAndValue(() =&gt; maxNumber);\n        string longVariableName = longVariable.Item1;\n        long longVariableValue = longVariable.Item2;\n\n        /*Test : user define types*/\n        Person aPerson = new Person() { Id = "123", Name = "Roy" };\n        Tuple&lt;string, Person&gt; personVariable = Utility.GetNameAndValue(() =&gt; aPerson);\n        string personVariableName = personVariable.Item1;\n        Person personVariableValue = personVariable.Item2;\n\n        /*Test : anonymous types*/\n        var ann = new { Id = "123", Name = "Roy" };\n        var annVariable = Utility.GetNameAndValue(() =&gt; ann);\n        string annVariableName = annVariable.Item1;\n        var annVariableValue = annVariable.Item2;\n\n        /*Test : Enum tyoes*/\n        Active isActive = Active.Yes;\n        Tuple&lt;string, Active&gt; isActiveVariable = Utility.GetNameAndValue(() =&gt; isActive);\n        string isActiveVariableName = isActiveVariable.Item1;\n        Active isActiveVariableValue = isActiveVariable.Item2;\n    }\n</code></pre>\n'}, {'answer_id': 21219225, 'author': 'blooop', 'author_id': 951520, 'author_profile': 'https://Stackoverflow.com/users/951520', 'pm_score': 4, 'selected': False, 'text': "<p><strong>Yes!</strong>  It is possible.  I have been looking for a solution to this for a long time and have finally come up with a hack that solves it (it's a bit nasty).  I would not recommend using this as part of your program and I only think it works in debug mode.  For me this doesn't matter as I only use it as a debugging tool in my console class so I can do:</p>\n\n<pre><code>int testVar = 1;\nbool testBoolVar = True;\nmyConsole.Writeline(testVar);\nmyConsole.Writeline(testBoolVar);\n</code></pre>\n\n<p>the output to the console would be:</p>\n\n<pre><code>testVar: 1\ntestBoolVar: True\n</code></pre>\n\n<p>Here is the function I use to do that (not including the wrapping code for my console class.</p>\n\n<pre><code>    public Dictionary&lt;string, string&gt; nameOfAlreadyAcessed = new Dictionary&lt;string, string&gt;();\n    public string nameOf(object obj, int level = 1)\n    {\n        StackFrame stackFrame = new StackTrace(true).GetFrame(level);\n        string fileName = stackFrame.GetFileName();\n        int lineNumber = stackFrame.GetFileLineNumber();\n        string uniqueId = fileName + lineNumber;\n        if (nameOfAlreadyAcessed.ContainsKey(uniqueId))\n            return nameOfAlreadyAcessed[uniqueId];\n        else\n        {\n            System.IO.StreamReader file = new System.IO.StreamReader(fileName);\n            for (int i = 0; i &lt; lineNumber - 1; i++)\n                file.ReadLine();\n            string varName = file.ReadLine().Split(new char[] { '(', ')' })[1];\n            nameOfAlreadyAcessed.Add(uniqueId, varName);\n            return varName;\n        }\n    }\n</code></pre>\n"}, {'answer_id': 24078293, 'author': 'kernowcode', 'author_id': 2088673, 'author_profile': 'https://Stackoverflow.com/users/2088673', 'pm_score': 2, 'selected': False, 'text': '<p>Do this</p>\n\n<pre><code>var myVariable = 123;\nmyVariable.Named(() =&gt; myVariable);\nvar name = myVariable.Name();\n// use name how you like\n</code></pre>\n\n<p>or naming in code by hand</p>\n\n<pre><code>var myVariable = 123.Named("my variable");\nvar name = myVariable.Name();\n</code></pre>\n\n<p>using this class</p>\n\n<pre><code>public static class ObjectInstanceExtensions\n{\n    private static Dictionary&lt;object, string&gt; namedInstances = new Dictionary&lt;object, string&gt;();\n\n    public static void Named&lt;T&gt;(this T instance, Expression&lt;Func&lt;T&gt;&gt; expressionContainingOnlyYourInstance)\n    {\n        var name = ((MemberExpression)expressionContainingOnlyYourInstance.Body).Member.Name;\n        instance.Named(name);            \n    }\n\n    public static T Named&lt;T&gt;(this T instance, string named)\n    {\n        if (namedInstances.ContainsKey(instance)) namedInstances[instance] = named;\n        else namedInstances.Add(instance, named);\n        return instance;\n    }        \n\n    public static string Name&lt;T&gt;(this T instance)\n    {\n        if (namedInstances.ContainsKey(instance)) return namedInstances[instance];\n        throw new NotImplementedException("object has not been named");\n    }        \n}\n</code></pre>\n\n<p>Code tested and most elegant I can come up with.</p>\n'}, {'answer_id': 32314158, 'author': 'johnny 5', 'author_id': 1938988, 'author_profile': 'https://Stackoverflow.com/users/1938988', 'pm_score': 5, 'selected': False, 'text': '<p>This isn\'t exactly possible, the way you would want.  C# 6.0 they Introduce the nameof Operator which should help improve and simplify the code.  The name of operator resolves the name of the variable passed into it.</p>\n<p>Usage for your case would look like this:</p>\n<pre><code>public string ExampleFunction(string variableName) {\n    //Construct your log statement using c# 6.0 string interpolation\n    return $&quot;Error occurred in {variableName}&quot;;\n}\n\nstring WhatIsMyName = &quot;Hello World&quot;;\nstring Hello = ExampleFunction(nameof(WhatIsMyName));\n</code></pre>\n<p>A major benefit is that it is done at compile time,</p>\n<blockquote>\n<p>The nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an &quot;unreachable code&quot; warning).</p>\n</blockquote>\n<p>More information can be found <a href="https://msdn.microsoft.com/en-us/magazine/Dn802602.aspx" rel="noreferrer">here</a></p>\n<p><strong>Older Version Of C 3.0 and above</strong><br />\nTo Build on Nawfals answer</p>\n<pre><code>GetParameterName2(new { variable });\n\n//Hack to assure compiler warning is generated specifying this method calling conventions\n[Obsolete(&quot;Note you must use a single parametered AnonymousType When Calling this method&quot;)]\npublic static string GetParameterName&lt;T&gt;(T item) where T : class\n{\n    if (item == null)\n        return string.Empty;\n\n    return typeof(T).GetProperties()[0].Name;\n}\n</code></pre>\n'}, {'answer_id': 57970296, 'author': 'Bjarne', 'author_id': 4964865, 'author_profile': 'https://Stackoverflow.com/users/4964865', 'pm_score': 3, 'selected': False, 'text': "<p>This would be very useful to do in order to create good exception messages causing people to be able to pinpoint errors better. Line numbers help, but you might not get them in prod, and when you do get them, if there are big statements in code, you typically only get the first line of the whole statement.</p>\n\n<p>For instance, if you call .Value on a nullable that isn't set, you'll get an exception with a failure message, but as this functionality is lacking, you won't see what property was null. If you do this twice in one statement, for instance to set parameters to some method, you won't be able to see what nullable was not set.</p>\n\n<p>Creating code like Verify.NotNull(myvar, nameof(myvar)) is the best workaround I've found so far, but would be great to get rid of the need to add the extra parameter.</p>\n"}, {'answer_id': 67240523, 'author': 'Serdar', 'author_id': 638990, 'author_profile': 'https://Stackoverflow.com/users/638990', 'pm_score': 0, 'selected': False, 'text': '<p>A way to get it can be reading the code file and splitting it with comma and parenthesis...</p>\n<pre><code>var trace = new StackTrace(true).GetFrame(1);\nvar line = File.ReadAllLines(trace.GetFileName())[trace.GetFileLineNumber()];\nvar argumentNames = line.Split(new[] { &quot;,&quot;, &quot;(&quot;, &quot;)&quot;, &quot;;&quot; }, \n                               StringSplitOptions.TrimEntries)\n                        .Where(x =&gt; x.Length &gt; 0)\n                        .Skip(1).ToList();\n</code></pre>\n'}, {'answer_id': 68652267, 'author': 'fibriZo raZiel', 'author_id': 1934546, 'author_profile': 'https://Stackoverflow.com/users/1934546', 'pm_score': 3, 'selected': False, 'text': '<p>Continuing with the <code>Caller*</code> attribute series (i.e <code>CallerMemberName</code>, <code>CallerFilePath</code> and <code>CallerLineNumber</code>), <a href="https://learn.microsoft.com/es-es/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-5.0" rel="noreferrer">CallerArgumentExpressionAttribute</a> is available since C# Next (more info <a href="https://stackoverflow.com/a/64900663/1934546">here</a>).</p>\n<p>The following example is inspired by Paul Mcilreavy\'s <a href="https://blog.mcilreavy.com/articles/2018-08/caller-argument-expression-attribute" rel="noreferrer">The CallerArgumentExpression Attribute in C# 8.0</a>:</p>\n<pre><code>public static void ThrowIfNullOrWhitespace(this string self, \n             [CallerArgumentExpression(&quot;self&quot;)] string paramName = default)\n{\n    if (self is null)\n    {\n        throw new ArgumentNullException(paramName);\n    }\n\n    if (string.IsNullOrWhiteSpace(self))\n    {\n        throw new ArgumentOutOfRangeException(paramName, self, &quot;Value cannot be whitespace&quot;);\n    }        \n}\n</code></pre>\n'}, {'answer_id': 68816481, 'author': 'Tormod', 'author_id': 80577, 'author_profile': 'https://Stackoverflow.com/users/80577', 'pm_score': -1, 'selected': False, 'text': '<p>If I understand you correctly, you want the string &quot;WhatIsMyName&quot; to appear inside the Hello string.</p>\n<pre><code>string Hello = ExampleFunction(WhatIsMyName);\n</code></pre>\n<p>If the use case is that it increases the reusability of ExampleFunction and that Hello shall contain something like &quot;Hello, Peter (from WhatIsMyName)&quot;, then I think a solution would be to expand the ExampleFunction to accept:</p>\n<p>string Hello = ExampleFunction(WhatIsMyName,nameof(WhatIsMyName));</p>\n<p>So that the name is passed as a separate string. Yes, it is not exactly what you asked and you will have to type it twice. But it is refactor safe, readable, does not use the debug interface and the chance of Error is minimal because they appear together in the consuming code.</p>\n<pre><code>string Hello1 = ExampleFunction(WhatIsMyName,nameof(WhatIsMyName));\nstring Hello2 = ExampleFunction(SomebodyElse,nameof(SomebodyElse));\nstring Hello3 = ExampleFunction(HerName,nameof(HerName));\n</code></pre>\n'}, {'answer_id': 69441516, 'author': 'hossein sedighian', 'author_id': 10143546, 'author_profile': 'https://Stackoverflow.com/users/10143546', 'pm_score': 1, 'selected': False, 'text': '<p>thanks to visual studio 2022 , you can use this</p>\n<p>function</p>\n<pre><code>       public void showname(dynamic obj) {\n            obj.GetType().GetProperties().ToList().ForEach(state =&gt; {\n                NameAndValue($&quot;{state.Name}:{state.GetValue(obj, null).ToString()}&quot;);\n            });\n        }\n</code></pre>\n<p>to use</p>\n<pre><code>   var myname = &quot;dddd&quot;;\n   showname(new { myname });\n</code></pre>\n'}, {'answer_id': 70038692, 'author': 'Greg M', 'author_id': 17458960, 'author_profile': 'https://Stackoverflow.com/users/17458960', 'pm_score': 5, 'selected': False, 'text': '<p>I know this post is really old, but since there is now a way in C#10 compiler, I thought I would share so others know.</p>\n<p>You can now use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-6.0" rel="noreferrer">CallerArgumentExpressionAttribute</a> as shown</p>\n<pre><code>// Will throw argument exception if string IsNullOrEmpty returns true\npublic static void ValidateNotNullorEmpty(\n  this string str,\n  [CallerArgumentExpression(&quot;str&quot;)]string strName = null\n)\n{       \n  if (string.IsNullOrEmpty(str))\n  {\n    throw new ArgumentException($&quot;\'{strName}\' cannot be null or empty.&quot;, strName);\n  }\n}\n</code></pre>\n<p>Now call with:</p>\n<pre><code>param.ValidateNotNullorEmpty();\n</code></pre>\n<p>will throw error: <code>&quot;param cannot be null or empty.&quot;</code></p>\n<p>instead of &quot;str cannot be null or empty&quot;</p>\n'}, {'answer_id': 73902688, 'author': 'Andy', 'author_id': 1204153, 'author_profile': 'https://Stackoverflow.com/users/1204153', 'pm_score': 0, 'selected': False, 'text': '<p>Extending on <a href="https://stackoverflow.com/a/70038692/1204153">the accepted answer</a> for this question, here is how you\'d do it with <code>#nullable enable</code> source files:</p>\n<pre><code>internal static class StringExtensions\n{\n    public static void ValidateNotNull(\n        [NotNull] this string? theString,\n        [CallerArgumentExpression(&quot;theString&quot;)] string? theName = default)\n    {\n        if (theString is null)\n        {\n            throw new ArgumentException($&quot;\'{theName}\' cannot be null.&quot;, theName);\n        }\n    }\n\n    public static void ValidateNotNullOrEmpty(\n        [NotNull] this string? theString,\n        [CallerArgumentExpression(&quot;theString&quot;)] string? theName = default)\n    {\n        if (string.IsNullOrEmpty(theString))\n        {\n            throw new ArgumentException($&quot;\'{theName}\' cannot be null or empty.&quot;, theName);\n        }\n    }\n\n    public static void ValidateNotNullOrWhitespace(\n        [NotNull] this string? theString,\n        [CallerArgumentExpression(&quot;theString&quot;)] string? theName = default)\n    {\n        if (string.IsNullOrWhiteSpace(theString))\n        {\n            throw new ArgumentException($&quot;\'{theName}\' cannot be null or whitespace&quot;, theName);\n        }\n    }\n}\n</code></pre>\n<p>What\'s nice about this code is that it uses <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.notnullattribute?view=net-6.0" rel="nofollow noreferrer"><code>[NotNull]</code></a> attribute, so the static analysis will cooperate:</p>\n<p><a href="https://i.stack.imgur.com/35I8C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/35I8C.png" alt="static analysis" /></a></p>\n'}]
['https://Stackoverflow.com/questions/72121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/383/']