C# get name of object pair - c#

var myObject = new { Id = 0, Name = "Test" };
I would like to get key name into variable in other part of project for ex.:
var keyName = someObject[0]; //someObject is passed myObject;
var value = someObject[1];
//Output keyName = Id; value = 0;
I know that dictionary would be good, but I have to stick to the delaration of myObject;

You can access the properties of your object this way:
myObject.GetType().GetProperties()
and the names e.g.
myObject.GetType().GetProperties()[0].Name //("Id")

It is not possible to do this with reflection, because variables won't have a name once compiled to IL. However, you can use expression trees and promote the variable to a closure:
static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
You can use this method as follows:
static void Main()
{
var someVar = 3;
Console.Write(GetVariableName(() => someVar));
}
Note that this is pretty slow, so don't use it in performance critical paths of your application.
For a more complete example, see here.

Related

Entity Framework - How to reference a column name using a string variable

I have a table called "Account." Account has 3 columns: id, acct_name, is_privileged.
When I write something like "account.", visual studio provides me with a list of attributes/methods I can use. Hence, I get the option of using account.id, account.acct_name, and account.is_privileged.
However, I would like to change a particular column's value dynamically, without typing in my column's name. I am getting the column's name dynamically as a string variable. Is it possible to achieve it? If so, how?
My code is as follows:
set_col_name = rowRule.Cells["setcolumnnameDataGridViewTextBoxColumn"].Value.ToString();
set_col_value = rowRule.Cells["setcolumnvalueDataGridViewTextBoxColumn"].Value.ToString();
foreach (DataGridViewRow rowAcc in dgvAccount.Rows)
{
if (isComparable(rowAcc.Cells[col_name].Value.ToString(), comp_operator, col_value))
{
account.id = (int)rowAcc.Cells["idDataGridViewTextBoxColumn2"].Value;
using (ae = new AccountEntities())
{
var temp = ae.Accounts.SingleOrDefault(a => a.id == account.id);
temp.is_privileged = set_col_value; //learn how to do this dynamically
ae.SaveChanges();
}
}
}
Where I do temp.is_privileged, I'd like to achieve something like, temp."set_col_name" = set_col_value;
Instead of specifying the column name directly as being "is_privileged" in this case, I'd like to pass a string to specify it.
Thank you.
If I understand your problem statement correctly, you want something like this to work:
Account temp = // with temp coming from a library such as EntityFramework
temp.SetValue(set_col_name, set_col_value);
this is quite easy to achieve with either pure reflection or Linq Expression Trees (which I opted for):
static class Ext
{
public static void Set<T, TProperty>(this T instance, string propertyName, TProperty value)
{
var instanceExpression = Expression.Parameter(typeof(T), "p");
var propertyGetterExpression = Expression.PropertyOrField(instanceExpression, propertyName);
//generate setter
var newValueExpression = Expression.Parameter(typeof(TProperty), "value");
var assignmentExpression = Expression.Assign(propertyGetterExpression, newValueExpression);
var lambdaExpression = Expression.Lambda<Action<T, TProperty>>(assignmentExpression, instanceExpression, newValueExpression);
var setter = lambdaExpression.Compile();// the generated lambda will look like so: (p, value) => p.{your_property_name} = value;
setter(instance, value);
}
}
one advantage of this method over pure reflection is that you can build the setter delegate once and call it multiple times at later stage (I will leave this with you to experiment)
with the above in place, hopefully you should be able to do something like this:
var set_col_name = "is_privileged";
var set_col_value = true;
using (ae = new AccountEntities())
{
var temp = ae.Accounts.SingleOrDefault(a => a.id == account.id);
temp.Set(set_col_name, set_col_value);
temp.Set("acct_name", "test");
ae.SaveChanges();
}
You need some reflection in this one. For example
public static void CopyValues<T>(T obj1, T obj2)
{
var type = typeof(T);
foreach (var prop in type.GetProperties())
{
prop.SetValue(obj1, prop.GetValue(obj2));
}
}
And use the above function like this:
var source = new Accounts(){is_privileged = false};
var destiny = new Accounts();
CopyValues(source, destiny);
It depends of what you are loking for, but the key is to use REFLECTION!

How to use a variable to access an object member in c#

I have a web service that returns a custom object (a struct type) APIStruct user.
I have a variable holding the name of the current field it is checking for currentField.
Now, in a situation where user contains first_name and last_name, I can access the value using user.first_name or user.last_name. BUT, is it possible to hold the field name in a variable and access the value through the variable? working like:
var currentField = "first_name";
var value = user.currentField;
Obviously the above is not working, so is there any way to do this? In the past with languages such as PowerShell it works just like above $currentField = "first_name"; $value = user.$currentField
I've tried user.currentField user.(currentField) user[currentField] user.$currentField
You can extend your object class to support access to a Dictionary of additional properties, accessible through an explicit indexer.
public class myClass
{
private Dictionary<string, object> Something = new Dictionary<string, object>();
public object this[string i]
{
get { return Something[i]; }
set { Something[i] = value; }
}
}
Use like this:
myClass m = new myClass();
Set value:
m["fist name"] = "Name";
m["level"] = 2;
m["birthday"] = new DateTime(2015, 1, 1);
Get value:
int level = (int)m["level"];
string firstName = (string)m["first name"];
DateTime dt = (DateTime)m["birthday"];
you must use reflection. Create a method like this:
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
and call it:
string currentField = "first_name";
GetPropValue(user, currentField);
But it must be said, it is not the way you should use for the standard reading of object values.
What you're looking for called Reflection.
var type = user.GetType(); // Get type object
var property = type.GetProperty(currentField); // get property info object
var value = property.GetValue(user); // get value from object.
Be careful - reflection is pretty slow compared to direct property access.
Another option you may have is to use a switch statement. Something like:
switch (currentField){
case "first_name":
value = user.first_name;
break;
case "last_name":
value = user.last_name;
break;
etc...

Expression Tree with string assignment and getting value

I have built my own SQL Query builder that breaks apart an Expression, however, I'm having an issue trying to get the value of string defined in the same function as the lambda expression.
Here is what I am trying to do in console app:
private static void MyBuilderTest()
{
var sqlBuilder = new SqlBuilder();
// Doesn't work -- NEED GUIDANCE HERE
var testValue = "Test"; // Defined in the same function as the lambda below
sqlBuilder.Select<FooObject>(o => o.FooValue == testValue);
// Works
var someObject = new SomeObject { SomeValue = "classTest };
sqlBuilder.Select<FooObject>(o => o.FooValue == someObject.SomeValue);
}
In my builder it subclasses from ExpressionVisitor, and I override the VisitMember. I found that a string defined in at the base Console level will come back as:
Node.Expression.NodeType == ExpressionType.Constant
The Node.Expression passes back properties of:
CanReduce = false
DebugView = ".Constant<ConsoleApplication1.Program+<>c__DisplayClass1>(ConsoleApplication1.Program+<>c__DisplayClass1)"
NodeType = Constant
Type = System.Type {System.RunetimeType}
Value = {ConsoleApplication1.Program}
The Node.Expression.Value contains:
testValue = "Test" (Type: string)
How do I get this value? I've tried several things, like:
var memberType = node.Expression.Type.DeclaringType;
This passes back a ConsoleApplication1.Program type.
However, when I do:
memberType.GetProperty("testValue"); // Declaring Type from Expression
It passes back null.
The above methods work fine if I place the lambda "strings" in a class, but doesn't work if they string is defined in the console function.
Can anyone tell me how to get the string value if it's defined at the function level of the lambda?
EDITED: Added VisitMember
protected override Expression VisitMember(MemberExpression node)
{
if (node.NodeType == ExpressionType.Constant)
{
// Node.Expression is a ConstantExpression type.
// node.Expression contains properties above
// And Has Value of: {ConsoleApplication1.Program}
// Expanding Value in Watch window shows: testValue = "Test"
// How do I get this value, if the ConsoleApplication1.Program type doesn't
// even know about it? Looks like maybe a dynamic property?
}
}
EDITED
Added code to the console app example to show what works and what doesn't.
The lambda in your example has "closed over" the testValue variable, meaning the compiler has captured it as a field of the same name in an automatically generated class called ConsoleApplication1.Program+<>c__DisplayClass1>. You can use normal reflection to get the current value of that field by casting the right hand-side of the binary expression into a MemberExpression.
var testValue = "hello";
var expr = (Expression<Func<string, bool>>) (x => x == testValue);
var rhs = (MemberExpression) ((BinaryExpression) expr.Body).Right;
var obj = ((ConstantExpression) rhs.Expression).Value;
var field = (FieldInfo) rhs.Member;
var value = field.GetValue(obj);
Debug.Assert(Equals(value, "hello"));
testValue = "changed";
value = field.GetValue(obj);
Debug.Assert(Equals(value, "changed"));
Alternatively you can change your variable into a constant.
const string testValue = "hello";
var expr = (Expression<Func<string, bool>>) (x => x == testValue);
var value = ((ConstantExpression) ((BinaryExpression) expr.Body).Right).Value;
Debug.Assert(Equals(value, "hello"));
Instead of doing this by yourself, have a look at PartialEvaluator from Matt Warren. It replaces all references to constants with the constants themselves.

Assigning property of anonymous type via anonymous method

I am new in the functional side of C#, sorry if the question is lame.
Given the following WRONG code:
var jobSummaries = from job in jobs
where ...
select new
{
ID = job.ID,
Description = job.Description,
FileName = (job) => {
// primitive logic not
// worth to become a named method
try { return job.Files[0].LocalName); }
catch { return null as string; }
}
};
This code produces the following justified compiler error:
cannot assign lambda expression to
anonymous type property
The code above would set the delegate to the FileName property. But that is not my aim. I want the code work like this but without naming the method:
var jobSummaries = from job in jobs
where ...
select new
{
ID = job.ID,
Description = job.Description,
FileName = this.ExtractFileName(job)
};
...
private string ExtractFileName(Job job)
{
try { return Path.GetFileName(job.Files[0].LocalName); }
catch { return null as string; }
}
Any suggestions?
To call an anonymous function directly, this works:
int result = new Func<int, int>( (int i) =>{ return i + 5; } ).Invoke(3);
// result = 8
But I agree, int result = (i => i + 5)(3); would be way cooler =)
As far as I know, you can't inline lambda expressions like that because a lamda expression is an instance itself (of the type Expression<Func<T>> or similar).
However, you can do this (updated with calculation of fileName, since this is now provided by the OP):
var jobSummaries = from job in jobs
where ...
let fileName = job.Files.Select(f => f.LocalName).FirstOrDefault()
select new
{
ID = job.ID,
Description = job.Description,
FileName = fileName
};
Notice the use of the let keyword, that lets you extract the filename from the job variable directly inside the LINQ expression.
The compiler is complaining because you are not calling your lambda function, you are defining it. If the compiler would let you, you'd have a FileName property that is a function rather than a value.
If you can write your "primitive logic" as an expression, you can write that directly in the assignment statement.
How about using extension for select. So you can do your little logic inside
var jobSummaries = jobs.Select(j =>
{
var someVar = j + "bla";
return new
{
somelogic = someVar
};
});

How can I get the name of a variable passed into a function?

Let me use the following example to explain my question:
public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(WhatIsMyName);
When I pass the variable WhatIsMyName to the ExampleFunction, I want to be able to get a string of the original variable's name. Perhaps something like:
Variable.OriginalName.ToString() // == "WhatIsMyName"
Is there any way to do this?
What you want isn't possible directly but you can use Expressions in C# 3.0:
public void ExampleFunction(Expression<Func<string, string>> f) {
Console.WriteLine((f.Body as MemberExpression).Member.Name);
}
ExampleFunction(x => WhatIsMyName);
Note that this relies on unspecified behaviour and while it does work in Microsoft’s current C# and VB compilers, and in Mono’s C# compiler, there’s no guarantee that this won’t stop working in future versions.
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.
Usage for your case would look like this:
public string ExampleFunction(string variableName) {
//Construct your log statement using c# 6.0 string interpolation
return $"Error occurred in {variableName}";
}
string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(nameof(WhatIsMyName));
A major benefit is that it is done at compile time,
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 "unreachable code" warning).
More information can be found here
Older Version Of C 3.0 and above
To Build on Nawfals answer
GetParameterName2(new { variable });
//Hack to assure compiler warning is generated specifying this method calling conventions
[Obsolete("Note you must use a single parametered AnonymousType When Calling this method")]
public static string GetParameterName<T>(T item) where T : class
{
if (item == null)
return string.Empty;
return typeof(T).GetProperties()[0].Name;
}
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.
You can now use CallerArgumentExpressionAttribute as shown
// Will throw argument exception if string IsNullOrEmpty returns true
public static void ValidateNotNullorEmpty(
this string str,
[CallerArgumentExpression("str")]string strName = null
)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentException($"'{strName}' cannot be null or empty.", strName);
}
}
Now call with:
param.ValidateNotNullorEmpty();
will throw error: "param cannot be null or empty."
instead of "str cannot be null or empty"
static void Main(string[] args)
{
Console.WriteLine("Name is '{0}'", GetName(new {args}));
Console.ReadLine();
}
static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
Enforce.That(properties.Length == 1);
return properties[0].Name;
}
More details are in this blog post.
Three ways:
1) Something without reflection at all:
GetParameterName1(new { variable });
public static string GetParameterName1<T>(T item) where T : class
{
if (item == null)
return string.Empty;
return item.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}
2) Uses reflection, but this is way faster than other two.
GetParameterName2(new { variable });
public static string GetParameterName2<T>(T item) where T : class
{
if (item == null)
return string.Empty;
return typeof(T).GetProperties()[0].Name;
}
3) The slowest of all, don't use.
GetParameterName3(() => variable);
public static string GetParameterName3<T>(Expression<Func<T>> expr)
{
if (expr == null)
return string.Empty;
return ((MemberExpression)expr.Body).Member.Name;
}
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:
1)
public static string GetParameterInfo1<T>(T item) where T : class
{
if (item == null)
return string.Empty;
var param = item.ToString().TrimStart('{').TrimEnd('}').Split('=');
return "Parameter: '" + param[0].Trim() +
"' = " + param[1].Trim();
}
2)
public static string GetParameterInfo2<T>(T item) where T : class
{
if (item == null)
return string.Empty;
var param = typeof(T).GetProperties()[0];
return "Parameter: '" + param.Name +
"' = " + param.GetValue(item, null);
}
3)
public static string GetParameterInfo3<T>(Expression<Func<T>> expr)
{
if (expr == null)
return string.Empty;
var param = (MemberExpression)expr.Body;
return "Parameter: '" + param.Member.Name +
"' = " + ((FieldInfo)param.Member).GetValue(((ConstantExpression)param.Expression).Value);
}
1 and 2 are of comparable speed now, 3 is again sluggish.
Yes! 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:
int testVar = 1;
bool testBoolVar = True;
myConsole.Writeline(testVar);
myConsole.Writeline(testBoolVar);
the output to the console would be:
testVar: 1
testBoolVar: True
Here is the function I use to do that (not including the wrapping code for my console class.
public Dictionary<string, string> nameOfAlreadyAcessed = new Dictionary<string, string>();
public string nameOf(object obj, int level = 1)
{
StackFrame stackFrame = new StackTrace(true).GetFrame(level);
string fileName = stackFrame.GetFileName();
int lineNumber = stackFrame.GetFileLineNumber();
string uniqueId = fileName + lineNumber;
if (nameOfAlreadyAcessed.ContainsKey(uniqueId))
return nameOfAlreadyAcessed[uniqueId];
else
{
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
for (int i = 0; i < lineNumber - 1; i++)
file.ReadLine();
string varName = file.ReadLine().Split(new char[] { '(', ')' })[1];
nameOfAlreadyAcessed.Add(uniqueId, varName);
return varName;
}
}
Continuing with the Caller* attribute series (i.e CallerMemberName, CallerFilePath and CallerLineNumber), CallerArgumentExpressionAttribute is available since C# Next (more info here).
The following example is inspired by Paul Mcilreavy's The CallerArgumentExpression Attribute in C# 8.0:
public static void ThrowIfNullOrWhitespace(this string self,
[CallerArgumentExpression("self")] string paramName = default)
{
if (self is null)
{
throw new ArgumentNullException(paramName);
}
if (string.IsNullOrWhiteSpace(self))
{
throw new ArgumentOutOfRangeException(paramName, self, "Value cannot be whitespace");
}
}
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.
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.
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.
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.
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.
Well Try this Utility class,
public static class Utility
{
public static Tuple<string, TSource> GetNameAndValue<TSource>(Expression<Func<TSource>> sourceExpression)
{
Tuple<String, TSource> result = null;
Type type = typeof (TSource);
Func<MemberExpression, Tuple<String, TSource>> process = delegate(MemberExpression memberExpression)
{
ConstantExpression constantExpression = (ConstantExpression)memberExpression.Expression;
var name = memberExpression.Member.Name;
var value = ((FieldInfo)memberExpression.Member).GetValue(constantExpression.Value);
return new Tuple<string, TSource>(name, (TSource) value);
};
Expression exception = sourceExpression.Body;
if (exception is MemberExpression)
{
result = process((MemberExpression)sourceExpression.Body);
}
else if (exception is UnaryExpression)
{
UnaryExpression unaryExpression = (UnaryExpression)sourceExpression.Body;
result = process((MemberExpression)unaryExpression.Operand);
}
else
{
throw new Exception("Expression type unknown.");
}
return result;
}
}
And User It Like
/*ToDo : Test Result*/
static void Main(string[] args)
{
/*Test : primivit types*/
long maxNumber = 123123;
Tuple<string, long> longVariable = Utility.GetNameAndValue(() => maxNumber);
string longVariableName = longVariable.Item1;
long longVariableValue = longVariable.Item2;
/*Test : user define types*/
Person aPerson = new Person() { Id = "123", Name = "Roy" };
Tuple<string, Person> personVariable = Utility.GetNameAndValue(() => aPerson);
string personVariableName = personVariable.Item1;
Person personVariableValue = personVariable.Item2;
/*Test : anonymous types*/
var ann = new { Id = "123", Name = "Roy" };
var annVariable = Utility.GetNameAndValue(() => ann);
string annVariableName = annVariable.Item1;
var annVariableValue = annVariable.Item2;
/*Test : Enum tyoes*/
Active isActive = Active.Yes;
Tuple<string, Active> isActiveVariable = Utility.GetNameAndValue(() => isActive);
string isActiveVariableName = isActiveVariable.Item1;
Active isActiveVariableValue = isActiveVariable.Item2;
}
Do this
var myVariable = 123;
myVariable.Named(() => myVariable);
var name = myVariable.Name();
// use name how you like
or naming in code by hand
var myVariable = 123.Named("my variable");
var name = myVariable.Name();
using this class
public static class ObjectInstanceExtensions
{
private static Dictionary<object, string> namedInstances = new Dictionary<object, string>();
public static void Named<T>(this T instance, Expression<Func<T>> expressionContainingOnlyYourInstance)
{
var name = ((MemberExpression)expressionContainingOnlyYourInstance.Body).Member.Name;
instance.Named(name);
}
public static T Named<T>(this T instance, string named)
{
if (namedInstances.ContainsKey(instance)) namedInstances[instance] = named;
else namedInstances.Add(instance, named);
return instance;
}
public static string Name<T>(this T instance)
{
if (namedInstances.ContainsKey(instance)) return namedInstances[instance];
throw new NotImplementedException("object has not been named");
}
}
Code tested and most elegant I can come up with.
Thanks for all the responses. I guess I'll just have to go with what I'm doing now.
For those who wanted to know why I asked the above question. I have the following function:
string sMessages(ArrayList aMessages, String sType) {
string sReturn = String.Empty;
if (aMessages.Count > 0) {
sReturn += "<p class=\"" + sType + "\">";
for (int i = 0; i < aMessages.Count; i++) {
sReturn += aMessages[i] + "<br />";
}
sReturn += "</p>";
}
return sReturn;
}
I send it an array of error messages and a css class which is then returned as a string for a webpage.
Every time I call this function, I have to define sType. Something like:
output += sMessages(aErrors, "errors");
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.
Again, thanks for all the responses.
thanks to visual studio 2022 , you can use this
function
public void showname(dynamic obj) {
obj.GetType().GetProperties().ToList().ForEach(state => {
NameAndValue($"{state.Name}:{state.GetValue(obj, null).ToString()}");
});
}
to use
var myname = "dddd";
showname(new { myname });
The short answer is no ... unless you are really really motivated.
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.
For example, what if the invocation was ExampleFunction("a" + "b")?
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.
Better go back to the drawing board on this one!
rp
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.
Well had a bit of look. of course you can't use any Type information.
Also, the name of a local variable is not available at runtime
because their names are not compiled into the assembly's metadata.
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):
static string sMessages(Expression<Func<List<string>>> aMessages) {
var messages = aMessages.Compile()();
if (messages.Count == 0) {
return "";
}
StringBuilder ret = new StringBuilder();
string sType = ((MemberExpression)aMessages.Body).Member.Name;
ret.AppendFormat("<p class=\"{0}\">", sType);
foreach (string msg in messages) {
ret.Append(msg);
ret.Append("<br />");
}
ret.Append("</p>");
return ret.ToString();
}
Call it like this:
var errors = new List<string>() { "Hi", "foo" };
var ret = sMessages(() => errors);
A way to get it can be reading the code file and splitting it with comma and parenthesis...
var trace = new StackTrace(true).GetFrame(1);
var line = File.ReadAllLines(trace.GetFileName())[trace.GetFileLineNumber()];
var argumentNames = line.Split(new[] { ",", "(", ")", ";" },
StringSplitOptions.TrimEntries)
.Where(x => x.Length > 0)
.Skip(1).ToList();
Extending on the accepted answer for this question, here is how you'd do it with #nullable enable source files:
internal static class StringExtensions
{
public static void ValidateNotNull(
[NotNull] this string? theString,
[CallerArgumentExpression("theString")] string? theName = default)
{
if (theString is null)
{
throw new ArgumentException($"'{theName}' cannot be null.", theName);
}
}
public static void ValidateNotNullOrEmpty(
[NotNull] this string? theString,
[CallerArgumentExpression("theString")] string? theName = default)
{
if (string.IsNullOrEmpty(theString))
{
throw new ArgumentException($"'{theName}' cannot be null or empty.", theName);
}
}
public static void ValidateNotNullOrWhitespace(
[NotNull] this string? theString,
[CallerArgumentExpression("theString")] string? theName = default)
{
if (string.IsNullOrWhiteSpace(theString))
{
throw new ArgumentException($"'{theName}' cannot be null or whitespace", theName);
}
}
}
What's nice about this code is that it uses [NotNull] attribute, so the static analysis will cooperate:
If I understand you correctly, you want the string "WhatIsMyName" to appear inside the Hello string.
string Hello = ExampleFunction(WhatIsMyName);
If the use case is that it increases the reusability of ExampleFunction and that Hello shall contain something like "Hello, Peter (from WhatIsMyName)", then I think a solution would be to expand the ExampleFunction to accept:
string Hello = ExampleFunction(WhatIsMyName,nameof(WhatIsMyName));
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.
string Hello1 = ExampleFunction(WhatIsMyName,nameof(WhatIsMyName));
string Hello2 = ExampleFunction(SomebodyElse,nameof(SomebodyElse));
string Hello3 = ExampleFunction(HerName,nameof(HerName));
No. I don't think so.
The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken.
If it helps, you could define a new class called NamedParameter with attributes Name and Param. You then pass this object around as parameters.

Categories