Can this be simplified with Lambda/Block initialization? - c#

Been bouncing back and forth between Swift and C# and I'm not sure if I'm forgetting certain things, or if C# just doesn't easily support what I'm after.
Consider this code which calculates the initial value for Foo:
// Note: This is a field on an object, not a local variable.
int Foo = CalculateInitialFoo();
static int CalculateInitialFoo() {
int x = 0;
// Perform calculations to get x
return x;
}
Is there any way to do something like this without the need to create the separate one-time-use function and instead use an instantly-executing lambda/block/whatever?
In Swift, it's simple. You use a closure (the curly-braces) that you instantly execute (open and closed parentheses), like this:
int Foo = {
int x = 0
// Perform calculations to get x
return x
}()
It's clear, concise and doesn't clutter up the object's interface with functions just to initialize fields.
Note: To be clear, I do NOT want a calculated property. I am trying to initialize a member field which requires multiple statements to do completely.

I wouldn't suggest doing this, but you could use an anonymous function to initialize
int _foo = new Func<int>(() =>
{
return 5;
})();
Is there a reason you would like to do it using lambdas rather than named functions, or as a calculated property?
I assume you want to avoid calculated properties because you want to either modify the value later, or the computation is expensive and you want to cache the value.
int? _fooBacking = null;
int Foo
{
get
{
if (!_fooBacking.HasValue)
{
_fooBacking = 5;
}
return _fooBacking.Value;
}
set
{
_fooBacking = value;
}
}
This will use what you evaluate in the conditional the first time it is gotten, while still allowing the value to be assigned.
If you remove the setter it will turn it into a cached calculation. Be careful when using this pattern, though. Side-effects in property getters will be frowned upon because they make the code difficult to follow.

To solve the problem in the general case you'd need to create and then execute an anonymous function, which you can technically do as an expression:
int Foo = new Func<int>(() =>
{
int x = 0;
// Perform calculations to get x
return x;
})();
You can clean this up a bit by writing a helper function:
public static T Perform<T>(Func<T> function)
{
return function();
}
Which lets you write:
int Foo = Perform(() =>
{
int x = 0;
// Perform calculations to get x
return x;
});
While this is better than the first, I think it's pretty hard to argue that either is better than just writing a function.
In the non-general case, many specific implementations can be altered to run on a single line rather than multiple lines. Such a solution may be possible in your case, but we couldn't possibly say without knowing what it is. There will be cases where this is possible but undesirable, and cases where this may actually be preferable. Which are which is of course subjective.

You could initialize your field in the constructor and declare CalculateInitialFoo as local function.
private int _foo;
public MyType()
{
_foo = CalculateInitialFoo();
int CalculateInitialFoo()
{
int x = 0;
// Perform calculations to get x
return x;
}
}
This won't change your code too much but you can at least limit the scope of the method to where it's only used.

Related

C# About the Ref<T> class i've found

Link to the class :
https://stackoverflow.com/a/4543089/6591306
My question is simple, the usage of the class is as so :
The getter is getting () => variable, and the setter is getting z => { variable = z; }
In order to call the function i call it like this :
ref<int> tempx;
int tempy = 5;
tempx=new Ref<int>(() => tempy, z => { tempy = z; });
tempy = 6;//tempx.Value becomes 6
tempx.Value = 7;//tempy becomes 7
I want to achieve that in order to call the class i'll do it :
tempx=new Ref<int>(tempy);
without writing the actions, so that it won't take alot of lines of code, and the actions will be saved in the class, and whenever i call it they'll be performed automatically.
I dont know how to achieve it, therefore i'm asking here.
You can't. There's no way to pass in an int and end up with the ability to get or set it at some arbitrary point in time in the future; you need to create lambdas in order to be able to do that.
I know this is an old question, but this extension method works for me:
public static Ref<T> GetRef<T>(this T obj)
{
return new Ref<T>(()=>obj,x=>obj=x);
}
You use it like this:
Ref<targetType> yourRefName=target.GetRef<targetType>();
or in your case:
tempx=tempy.GetRef<int>();
Edit: This only works for classes, not value types like ints, so doesn't help with this specific question

Is there an accepted pattern to preserve variables' values during a function call which modifies those variables?

Within a class I have a property used by a method which I want to remain in the same state after a call to a second method (which might alter that state).
Example: for a property Value I could do something like this:
void MethodOne()
{
...
var tempValue = this.Value;
MethodTwo(); // might modify this.Value
this.Value = tempValue;
...
}
For a single property this isn't a big deal. If I have multiple properties it gets uglier.
I'm looking for a C# solution but would be interested to know if this kind of construct appears in any common language. The sort of syntax I'm after might look something like this:
void MethodOne()
{
...
preserving(this.Value)
{
MethodTwo(); // might modify this.Value
}
...
}
where the preserving keyword could potentially accept multiple properties/fields.
In my specific case it's a recursive method, so the code looks more like:
void MethodOne(object[] args)
{
...
// Do something which might modify this.Value
preserving(this.Value)
{
MethodOne(args);
}
...
}
Is there an accepted pattern / best practice to achieve this?
EDIT
The specific case for which I'm asking is something like this:
For the purposes of sorting lists I have a custom comparison class which implements IComparer. Its Compare method acts on objects which appear in collections (which may therefore be sorted). These collections might be nested, so sorting such a collection might result in the sort function, and therefore Compare(), being called recursively.
The actual comparison function is partially dynamic, which means that it could be set at runtime to something invalid (e.g. non-transitive or non-deterministic). I can't prevent this, so I want to set a limit on the number of comparisons (let's say n-squared, where n is the length of the list being sorted) to protect against cases where an invalid comparison function might result in the sorting algorithm going into an infinite loop.
The Compare method might be called from (e.g.) various LINQ methods such as OrderBy, possibly resulting in lazily evaluated sorts and possibly from code over which I have no control. However, I need to count the number of comparisons in each sort without any 'subsorts' of nested objects corrupting the count (but also counting comparisons in those subsorts).
My code looks something like this:
public int Compare(T x, T y)
{
// this.MaxComparisons is set from outside this code, since this method does not know the length of the list it is sorting.
if (++this.ComparisonCount > this.MaxComparisons)
{
// Error: too many comparisons
}
if (predicate)
{
// Preserve...
tempComparisonCount = this.ComparisonCount;
tempMaxComparisons = this.MaxComparisons;
// ...reset...
this.ComparisonCount = 0;
this.MaxComparisons = ... ; // set as required
var result = this.customComparer.Compare(x.Child, y.Child); // might involve further calls to the above method, which should be counted separately
// ...and restore
this.ComparisonCount = tempComparisonCount;
this.MaxComparisons = tempMaxComparisons;
return result;
}
else
{
return otherComparer.Compare(x, y);
}
}
I hope this makes it clearer why I have asked the question.
private static void Preserving<T>(ref T value, Action act)
{
T old = value;
act();
value = old;
}
then you can do:
Preserving(ref this.Value, MethodTwo);
If you have multiple variables you want to save and restore, you should probably create a Context class containing the state you want to save and then push/pop them from a stack.

Why can't I edit a List member directly in C#

I have a class declared as public class DatumSet : List<datum>, where
public struct datum {
public UInt32[] chan;
public UInt64 sample_number;
public float time;
public UInt32 source_sector;
}
I want to iterate through the List and make some changes. Why does this NOT work
for (int i = 0; i < this.Count; i++) {
this[i].sample_number = startSample;
this[i].time = (float)startSample / _sample_rate;
startSample++;
}
but this DOES work
for (int i = 0; i < this.Count; i++) {
datum d = this[i];
d.sample_number = sampleNumber;
d.time = (float)sampleNumber / _sample_rate;
sampleNumber++;
}
I get the error:
Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable
This is what you get for using a mutable value type :)
Think of an indexer as just like a method call. So this:
this[i].sample_number = startSample;
is like:
GetValue(i).sample_number = startSample;
But because datum is a value type (a struct), the method is returning a copy of the value in the list - so modifying it would do you no good at all.
The compiler is stopping you from making that mistake.
You claim that this works:
for (int i = 0; i < this.Count; i++) {
datum d = this[i];
d.sample_number = sampleNumber;
d.time = (float)sampleNumber / _sample_rate;
sampleNumber++;
}
... but in reality, it does nothing useful. It's equivalent to:
sampleNumber += this.Count;
That's all. It compiles, but that's not the same as it working.
I would suggest that you make all value types immutable; it helps to prevent you from getting into this mess. So either you can keep datum as a value type, and replace the value in the list on each iteration, or you can change it to be a class, and modify the objects via the reference stored in the list.
(Either way, I'd strongly suggest that you start using properties instead of public fields, and start following .NET naming conventions too.)
You're having problems because you are using a struct rather than a class.
When you retrieve a struct from a collection, a copy is made. Your first set of code gives you an error because it detects you're doing something you may not mean to do. You'd actually be editing a copy of the struct rather than the copy in the collection.
The second doesn't produce an error because you explicitly pull the copy out of the collection before editing. This code may compile, but won't modify any of the structs in the collection and thus won't give you the results that you're expecting.

will declaring variables inside sub-blocks improve performance?

In C#, would there be any difference in performance when comparing the following THREE alternatives?
ONE
void ONE(int x) {
if (x == 10)
{
int y = 20;
int z = 30;
// do other stuff
} else {
// do other stuff
}
}
TWO
void TWO(int x) {
int y;
int z;
if (x == 10)
{
y = 20;
z = 30;
// do other stuff
} else {
// do other stuff
}
}
THREE
void THREE(int x) {
int y = 20;
int z = 30;
if (x == 10)
{
// do other stuff
} else {
// do other stuff
}
}
All else being equal (and they usually aren't, which is why you normally have to actually test it), ONE() and TWO() should generate the same IL instructions since local variables end up scoped to the whole method. THREE() will be negligibly slower if x==10 since the other two won't bother to store the values in the local variables.
All three take up the same amount of memory—the memory for all variables is allocated even if nothing is stored in them. The JIT compiler may perform an optimization here, though, if it ever looks for unused variables.
There no performance difference, but you're going to find variable scope issues between each of those examples.
You're also showing three different intents between those examples, which isn't what you want:
y and z are limited to the scope of the if statement.
y and z are used outside of the if statement, but are set conditionally.
y and z have nothing to do with the if statement whatsoever.
Of course, you should always pick ONE, it is much more readable. That it is faster by a fraction of a nanosecond isn't an accident, readable code often is.
I don't think it'll make much difference. The only time you would need to worry is if creating the new object and initializing it is expensive. You could always try to profile each method a couple thousand times to see if there are any differences but I doubt you'll find any.
The only time I move a declaration further away from where it's used is if it'll be worked on in a loop. e.g.:
void RunMethod() {
FormRepresentation formRep = null;
for (int idx = 0; idx < 10; idx++) {
formRep = new FormRepresentation();
// do something
}
}
It doesn't actually make any difference since the object is still being created but, to me, it looks cleaner. The other thing you need to consider is the scope of the variable. Declared variables cannot be used outside the scope they were declared in.

Reducing Duplicated Code

I have some code that works on the color structure like this
public void ChangeColor()
{
thisColor.R = thisColor.R + 5;
}
Now I need to make a method that changes a different variable depending on what it is passed. Here is what the code looks like now.
public void ChangeColor(int RGBValue)
{
switch(RGBValue)
{
case 1:
thisColor.R = thisColor.R + 5;
break;
case 2:
thiscolor.B = thisColor.B + 5;
break;
}
}
Now, this is something I would normally never question, I'd just throw a #region statement around it and call it a day, but this is just an example of what I have, the actual function is quite long.
I want it to look like this:
public void ChangeColor(int RGBValue)
{
thiscolor.RGBValue = thiscolor.RGBValue;
}
So essentially the value would refer to the variable being used. Is there a name for this? Is this what Reflection is for? Or something like that... Is there a way to do this?
I'm not 100% sure if this is what you want. But with the given example, it sounds like this might be what you're after.
you might be able to use the ref keyword:
public void ChangeColor(ref int color)
{
color += 5;
}
void SomeMethod()
{
ChangeColor(ref thisColor.R); //Change the red value
ChangeColor(ref thisColor.B); //Change the blue value
}
This is definitely not what reflection is for. In fact, there seem to be a number of issues here. Let's review here - you want to change the following method:
public void ChangeColor(int RGBValue)
{
switch(...)
{
case ...
case ...
case ...
}
}
Into something like this:
public void ChangeColor(int RGBValue)
{
thisColor.{something-from-RGBValue} += 5;
}
The problems with this are:
The name of the method, ChangeColor, does not precisely describe what the method actually does. Perhaps this is an artifact of anonymization, but nevertheless it's a terrible name for the method.
The parameter, RGBValue, does not accurately describe what the argument is or does. The name RGBValue and the type int makes it sound like an actual RGB color value, i.e. 0x33ccff for a light blue. Instead it chooses which of R, G, or B will be set.
There are only 3 valid values for the parameter, and yet the range of possible values is completely unrestricted. This is a recipe for bugs. Worse, individual values are used as magic numbers inside the method.
But perhaps most important of all, the "clean/quick method" you are asking for is precisely the abstraction that this method purports to provide! You're writing a method that intensifies the hue, and in order to keep the method short, you're asking for... a method to intensify the hue. It doesn't make sense!
I can only assume that you want to do this because you have many different things you might want to do to a Color, for example:
public void Brighten(...) { ... }
public void Darken(...) { ... }
public void Desaturate(...) { ... }
public void Maximize(...) { ... }
And so on and so forth. And you're trying to avoid writing switch statements for all.
Fine, but don't eliminate the switch entirely; it is by far the most efficient and readable way to write this code! What's more important is to distill it down to one switch instead of many, and fix the other problems mentioned above. First, let's start with a reasonable parameter type instead of an int - create an enumeration:
public enum PrimaryColor { Red, Green, Blue };
Now, start from the idea that there may be many actions we want to perform on one of the primary colors of a composite color, so write the generic method:
protected void AdjustPrimaryColor(PrimaryColor pc, Func<byte, byte> adjustFunc)
{
switch (pc)
{
case PrimaryColor.Red:
internalColor.R = adjustFunc(internalColor.R);
case PrimaryColor.Green:
internalColor.G = adjustFunc(internalColor.G);
default:
Debug.Assert(pc == PrimaryColor.Blue,
"Unexpected PrimaryColor value in AdjustPrimaryColor.");
internalColor.B = adjustFunc(internalColor.B);
}
}
This method is short, easy to read, and will likely never have to change. It is a good, clean method. Now we can write the individual action methods quite easily:
public void Brighten(PrimaryColor pc)
{
AdjustPrimaryColor(pc, v => v + 5);
}
public void Darken(PrimaryColor pc)
{
AdjustPrimaryColor(pc, v => v + 5);
}
public void Desaturate(PrimaryColor pc)
{
AdjustPrimaryColor(pc, v => 0);
}
public void Maximize(PrimaryColor pc)
{
AdjustPrimaryColor(pc, v => 255);
}
The (significant) advantages to this are:
The enumeration type prevents callers from screwing up and passing in an invalid parameter value.
The general Adjust method is easy to read and therefore easy to debug and easy to maintain. It's also going to perform better than any reflection-based or dictionary-based approach - not that performance is likely a concern here, but I'm mainly saying this to note that it certainly isn't going to be worse.
You don't have to write repeated switch statements. Each individual modifier method is exactly one line.
Eventually, somewhere, you're actually going to have to write some code, and I would much rather that code be an extremely simple switch statement than a mess of reflection, delegates, dictionaries, etc. The key is to generalize this work as much as possible; once you've done that and created that abstraction, then you can start writing one-liner methods to do the "real" work.
It's a bit awkward, but you can pass a property 'by ref' like this:
int ThisColor { get; set; }
public void ChangeColor(Func<int> getter, Action<int> setter)
{
setter(getter() + 5);
}
public void SomeMethod()
{
ChangeColor(() => ThisColor, (color) => ThisColor = color);
}
This is less expensive than reflection and it's compile-time checked (with reflection, you'd have to pass a string to a GetProperty call and the string name could potentially diverge from the property name in later refactoring.)
I would tend to use a dictionary rather than what i suspect could end up being a large switch statement so if you created a
Dictionary<int,Func<int,int>> map = new Dictionary<int, Func<int, int>>();
Each item in your dictionary could take then input and return the new value
so you your method you would be able to call
public int ChangeColor(int rgbValue)
{
return map[rgbValue](rgbValue);
}
which will execute the delegate specific for the Rgb value you insert, to assign a delegate you simply add a new entry to the map
map.Add(5,x => x+5);
If I understand you correctly, you'd like to write a method that takes some symbol (or property name) and modifies the property of the structure using defined by this symbol. This isn't easily possible in C# (you could of course use reflection, but...).
You could do similar thing using Dictionary containing delegates for reading and writing the value of the property. However, that will still be a bit lengthy, because you'll need to initialize the dictionary. Anyway, the code might look like this:
var props = new Dictionary<string, Tuple<Func<Color, int>, Action<Color, int>>>
{ "R", Tuple.Create(c => c.R, (c, r) => c.R = r),
"G", Tuple.Create(c => c.G, (c, g) => c.G = g),
"B", Tuple.Create(c => c.B, (c, b) => c.B = b) };
This creates a dictionary that contains string (name of the property) as the key and a tuple with getter delegate and setter delegate for each of the property. Now your ChangeColor method could look like this:
public void ChangeColor(string propName) {
var getSet = props[propName];
getSet.Item2(thisColor, getSet.Item1(thisColor) + 5);
}
The code would be more readable if you used your own type with Get property and Set property instead of Tuple with properties named Item1 and Item2. This solution may be useful in some scenarios, but you still need to explicitly list all the properties when initializing the dictionary.
This might be what your looking for, you may want to add some error handling though.
It will work with any kind of property with public get; and set; methods.
And if you want to there is ways to reduce use of "magic-strings".
public static void ChangeProperty<T>(this object obj, string propertyName, Func<T,T> func)
{
var pi = obj.GetType().GetProperty(propertyName);
pi.SetValue(obj, func((T)pi.GetValue(obj, null)), null);
}
public void Change()
{
thisColor.ChangeProperty<int>("R", (x) => x + 5);
}
Well, it's kind of hard to tell what's really going on since you've given a very simplified example.
But, what I'm really reading is that you want to have a method that will perform one of a number of possible modifications to local state based upon one of the parameters of the method.
Now, is the operation the same, except for what it's being done to?
Ultimately, you have to have some code that understandds that maps an input to a desired operation. How much that can be generalized depends upon how similar the actions are (if it's always 'add 5 to a property' you have more generalization options...).
Some options you have are:
Write a class which encapsulates the Color struct.
Use a lookup table of Actions, as suggested by Kev Hunter.
Write a switch statement.
Pass in a parameter which contains a virtual method which can be executed on the internal data (or just pass in an Action<> directly) - avoiding the lookup
And... that's about it, really. Which one of these makes the most sense probably depends more on your actual use case (which we don't really have a lot of info on) than anything else.

Categories

Resources