Reputation: 329
Is it possible to get an elements variable name in a foreach loop? I have tried nameof(v), which does not seem to work. See below:
//check for blank answer boxes and set flag for validation
foreach (string v in new object[] { answer3, answer4, answer5, answer6b, answer11, answer12, answer13b, answer14c, answer18, answer20 })
{
if (string.IsNullOrWhiteSpace(v))
{
s1.Flag = true;
s1.FlagContent += $"Blank answer box: {nameof(v)}. ";
}
}
For example, if answer3 was null or contained white space, s1.Flag would be set to true and s1.FlagContent would be set to "Blank answer box: answer3".
Upvotes: 0
Views: 1256
Reputation: 846
use a Dictionary:
string answer3 = "bla";
string answer4 = null;
string answer5 = "";
var answers = new Dictionary<string,string>();
answers.Add( nameof(answer3), answer3 );
answers.Add( nameof(answer4), answer4 );
answers.Add( nameof(answer5), answer5 );
foreach( var v in answers )
{
if (string.IsNullOrWhiteSpace(v.Value))
{
s1.Flag = true;
s1.FlagContent += $"Blank answer box: {v.Key}. ";
}
}
Upvotes: 2
Reputation: 52240
What you're asking is not possible. And when you consider that a given object may be referenced by any number of variables (all of which could have different names), this idea doesn't even make sense.
The typical way to handle this sort of scenario is to store the answers in a dictionary instead of giving them separate variables. If you absolutely have to have them in separate variables, you can convert them to a dictionary like this:
var dictionary = new Dictionary<string, string>
{
{ "answer1", answer1 },
{ "answer2", answer2 },
{ "answer3", answer3 },
{ "answer4", answer4 },
{ "answer5", answer5 }
};
Then the problem is trivial:
foreach (var item in dictionary)
{
if (string.IsNullOrWhiteSpace(item.Value))
{
s1.Flag = true;
s1.FlagContent += $"Blank answer box: {item.Key}.";
}
}
Upvotes: 2