I'd like to pass a class property (or a getter/setter if need be) reference to a function.
For example I have an array of a class with lots of boolean flags.
class Flags
{
public bool a;
public bool b;
public bool c;
public string name;
public Flags(bool a, bool b, bool c, string name)
{
this.a = a;
this.b = b;
this.c = c;
this.name = name;
}
}
I can write a method that returns all instances of Flags for which a chosen flag is true
public Flags[] getAllWhereAisTrue(Flags[] array)
{
List<Flags> resultList = new List<Flags>();
for (int i = 0; i < array.Length; i++)
{
if (array[i].a == true) // for each Flags for which a is true
{ // add it to the results list
resultList.Add(array[i]);
}
}
return resultList.ToArray(); //return the results list as an array
}
What would I use to allow me to pass a class property as a parameter, so as to save me from having to write this method once for each boolean property of Flags (in this example that's three times, once for a, b and c)?
I'm trying to avoid giving Flags an array of Booleans in an attempt to keep the resulting code easy to read. I'm writing a library for use by relatively inexperienced coders.
Thank you
(With apologies if this is a dupe of Passing property as parameter in method, I can't quite tell if it's the same issue)
In C# we can pass parameter to a class and the class which takes parameter is called parameterized class or generic class.
To pass a parameter by reference with the intent of changing the value, use the ref , or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier. For simplicity, only the ref keyword is used in the examples in this topic.
Parameters act as variables inside the method. They are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a string called fname as parameter.
You could use a Func<Flags, bool>
as parameter:
public Flags[] getAllWhereAisTrue(Flags[] array, Func<Flags, bool> propertySelector)
{
List<Flags> resultList = new List<Flags>();
for (int i = 0; i < array.Length; i++)
{
if (propertySelector(array[i])) // for each Flags for which a is true
{ // add it to the results list
resultList.Add(array[i]);
}
}
return resultList.ToArray(); //return the results list as an array
}
Then you could use it like this:
var allAFlagsSet = getAllWhereAisTrue(flagsArray, x=> x.a);
But really you should not reinvent this - Linq does this out of the box (notice the similarity):
var allAFlagsSet = flagsArray.Where(x=> x.a).ToArray();
Both solutions would require the a,b,c to be public (should really be a public property in this case)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With