How to get the name of a parameter? [duplicate] - c#

This question already has answers here:
get name of a variable or parameter [duplicate]
(3 answers)
What is the purpose of nameof?
(17 answers)
Closed 4 years ago.
I have a parameter d. I want to use the name of the parameter in an error message:
void foo(string d)
{
// this does not work
string message string.Format("Parameter {0} is missing please verify inputs", d));
}
How can I get the name of a parameter?

You can use nameof:
string nameOfD = nameof(d);
Note that this will not give the name of the variables used to call a method, it just works for the local variable. In this case, nameof will always return "d".

You can use Lambda expressions:
static void Main( string[] args ) {
int A = 50, B = 30, C = 17;
Print( () => A );
Print( () => B );
Print( () => C );
}
static void Print<T>( System.Linq.Expressions.Expression<Func<T>> input ) {
System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input;
System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body;
var result = input.Compile()();
Console.WriteLine( "{0}: {1}", member.Member.Name, result );
}
Try this one.

You could use a concatenation of String.IsNullOrEmpty(variable)?nameof(variable):String.Empty. So you'd get
var str = String.Join(',', new List<String>
{
String.IsNullOrEmpty(a)?nameof(a):String.Empty,
String.IsNullOrEmpty(b)?nameof(b):String.Empty,
String.IsNullOrEmpty(c)?nameof(c):String.Empty,
String.IsNullOrEmpty(d)?nameof(d):String.Empty
});
string.Format("Parameter {0} is missing please verify inputs", str);

Related

Optional parameter in lambda [duplicate]

This question already has answers here:
Can a Delegate have an optional parameter?
(2 answers)
Closed 9 years ago.
Why this piece of code does not compile?
delegate int xxx(bool x = true);
xxx test = f;
int f()
{
return 4;
}
Optional parameters are for use on the calling side - not on what is effectively like a single-method-interface implementation. So for example, this should compile:
delegate void SimpleDelegate(bool x = true);
static void Main()
{
SimpleDelegate x = Foo;
x(); // Will print "True"
}
static void Foo(bool y)
{
Console.WriteLine(y);
}
What will happen test(false)? It will corrupt the stack, because signatures must match.
Try this way:
static int f(bool a)
{
return 4;
}

Is it possible to write a function that can determine the original var name of a passed in param? [duplicate]

This question already has answers here:
How can I get the name of a variable passed into a function?
(23 answers)
Closed 2 years ago.
The basic goal is to write a function as such:
int myInt = 5;
PrettyPrint(myVar);
//in some helper class
public static void PrettyPrint<T>(T var) {
Console.WriteLine(/* ??? */ + ": " + var); //output: "myInt: 5"
}
I know we can do nameof(myVar) inline which would return "myVar", however, is it possible to abstract that into a function that lives somewhere else? If we do nameof in PrettyPrint, in this case it would return "var" and not the original name.
Now, I know you're thinking "just pass in a string for the name", but ultimately I'd like the following:
public static void PrettyPrintMany<T>(params T[] vars) {
string s = "";
foreach (T v in vars) {
s += <original name> + ": " + t + " | ";
}
Console.WriteLine(s);
}
int myInt = 5;
string myStr = cheese;
float myFloat = 3.14f;
PrettyPrintMany(v1, v2, v3); //"myInt: 5 | myStr: cheese | myFloat: 3.14 | "
I feel like this is not possible, but maybe there is some clever hackery that can be done?
The short answer is you cannot! the only way to have the variable name without using magic strings is using nameof which produces a constant string at compile time and not at runtime:
so this:
var hello = "there!";
Console.WriteLine(nameof(hello));
will compile to this
var hello = "there!";
Console.WriteLine("hello");
i am not much of a C++ developer but you can pass a sturcture and inside structure your variable and that way you can have the variable name exactly as it was sent

How to pass a function with parameters as an argument to a function? [duplicate]

This question already has answers here:
Cleanest way to write retry logic?
(30 answers)
Closed 2 years ago.
I wish to create an extension method that takes A function with a parameter of IEnumerable<T>.
int NumberOfRetries = 3;
string TableName = "Table";
Method(EnumerableParameter).RetrySection(EnumerableParameter,TableName ,NumberOfRetries);
Function to be extended
bool Method(IEnumerable<int> param)
{
foreach(var item in param)
{
Console.WriteLine(item);
}
return true;
}
I am having difficulty making the code compile
RetrySection(() => Method(EnumerableParameter),EnumerableParameter,TableName ,NumberOfRetries);
for both options.
Method(EnumerableParameter).RetrySection(EnumerableParameter,TableName,NumberOfRetries);
Extension Method
public static void RetrySection(this Func<IEnumerable<T>,bool> action, IEnumerable<T> parameter,string databaseTable,int jobcount)
{
int jobRowCount = ValidateTable(databaseTable).GetAwaiter().GetResult();
int retry = 0;
do
{
action(parameter);
jobRowCount = ValidateTable(databaseTable).GetAwaiter().GetResult();
retry++;
}
while ((jobRowCount < (jobcount * 2)) && retry < 3);
}
I'm getting the error Func<IEnumerable<int>,bool> does not take 0 arguments.
The solution is to use:
Method.RetrySection(EnumerableParameter,TableName ,NumberOfRetries);
because that is what RetrySection is defined to work on - Func<IEnumerable,bool>, instead of the result - bool.
Or, in case of the second example:
RetrySection(Method,EnumerableParameter,TableName ,NumberOfRetries);

compiler is printing Strange value in c# [duplicate]

This question already has answers here:
printing all contents of array in C#
(13 answers)
How does the .ToString() method work?
(4 answers)
Closed 6 years ago.
I am using methods in c#. i returned something but compiler is not printing which i am expecting. It is printing (system.string[]). i dont know why Please help on this.
class Program
{
static void Main(string[] args)
{
string[] sub = subjects();
Console.WriteLine(sub);
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
for (int i = 0; i < limit; i++)
{
Console.WriteLine("Please Enter Subject Name " + i);
Subjects[i] = Console.ReadLine();
}
return Subjects;
}
}
The reason that Program is printing system.string[] is because class string[] does not override ToString method, so the default one is used and the default ToString returns type name, not the "value" inside type.
You can use for example String.Join method to build one string from array of strings and put given delimiter between each string:
Console.WriteLine(String.Join(", ", sub));
Console.WriteLine(sub)
wont show you anything of value (it prints the sub type), since you are not referencing any value of the sub array, e.g sub[0]. Try this:
foreach (string s in sub)
{
Console.WriteLine(s);
}
Console.WriteLine(String.Join(", ", sub));

C# string method for exact match on multiple params [duplicate]

This question already has answers here:
How do you implement the equivalent of SQL IN() using .net
(9 answers)
Closed 6 years ago.
Is there a standard String method that can take multiple parameters for exact comparison?
The equivalent in T-SQL would be IN('dog','cat',...)
Eg, if there was such a method called EqualToAny() then the below code should return false
string s="catfish";
if (s.EqualToAny("dog", "cat", "human", "dolphin"))
return true;
else
return false;
You can achieve this using the Linq Any() method.
string input = "catfish";
var mammals = new [] {"dog", "cat", "human", "dolphin"};
var result = mammals.Any(v => v == input);
result will be false for "catfish" and true for "cat".
You can also wrap this into an extension method for string:
public static bool EqualsAny(this string str, IEnumerable<string> validStrings) {
return validStrings.Any(v => v == str);
}
var result = input.EqualsAny(mammals);
Fiddle
you need EqualsAny ..
// string extension method
public static bool EqualsAny(this string source, params string[] prms)
{
return prms.Contains(source);
}

Categories

Resources