Posts

Showing posts with the label C#

How to return a named tuple with only one field

10 1 I wrote a function in c# which initially returned a named tuple. But now, I only need one field of this tuple and I would like to keep the name because it helps me to understand my code. private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() { // do something return (true, false); } This function compile. But It's the following function that I want private static (bool informationAboutTheExecution) doSomething() { // do something return (true); } the error messages: Tuple must containt at least two elements cannot implcitly convvert type 'bool' to '(informationAboutTheExecution,?) Has somebody a solution to keep the name of the returned value? ...

What changed in .net 5 that makes it not throw when changing dictionary values in foreach

31 2 In .NET<5 and .NET Core 3.1 the following code var d = new Dictionary<string, int> { { "a", 0 }, { "b", 0 }, { "c", 0 } }; foreach (var k in d.Keys) { d[k]+=1; } throws System.InvalidOperationException: Collection was modified; enumeration operation may not execute. When targeting .NET 5 the snippet no longer throws. What has changed? I failed to find the answer in Breaking changes in .NET 5 and Performance Improvements in .NET 5. Is it something to do with ref readonly T ? c# .net-5 Share ...

Why does a zero-length stackalloc make the C# compiler happy to allow conditional stackallocs?

41 6 The following "fix" is very confusing to me; the scenario here is conditionally deciding whether to use the stack vs a leased buffer depending on the size - a pretty niche but sometimes-necessary optimization, however: with the "obvious" implementation (number 3, deferring definite assignment until we actually want to assign it), the compiler complains with CS8353: A result of a stackalloc expression of type 'Span<int>' cannot be used in this context because it may be exposed outside of the containing method The short repro (a complete repro follows) is: // take your pick of: // Span<int> s = stackalloc[0]; // works // Span<int> s = default; // fails // Span<int> s; // fails if (condition) { // CS8353 happ...

Round a decimal to the first decimal position that is not zero

I want to shorten a number to the first significant digit that is not 0. The digits behind should be rounded. Examples: 0.001 -> 0.001 0.00367 -> 0.004 0.00337 -> 0.003 0.000000564 -> 0.0000006 0.00000432907543029 -> 0.000004 Currently I have the following procedure: if (value < (decimal) 0.01) { value = Math.Round(value, 4); } Note: numbers will always be positive the number of significant digits will always be 1 values larger 0.01 will always be rounded to two decimal places, hence the if < 0.01 As you can see from the examples above, a rounding to 4 Decimal places might not be enough and the value might vary greatly. I would declare precision variable and use a loop iteration multiplies that variable by 10 with the original value it didn't hit, that precision will add 1. then use precision variable be Math.Round second parameter. static decimal RoundFirstSignificantDigit(decimal input) { int precision = 0; var val = input; while (Math.A...

Null coalescing operator IList, Array, Enumerable.Empty in foreach

In this question I found the following: int[] array = null; foreach (int i in array ?? Enumerable.Empty<int>()) { System.Console.WriteLine(string.Format("{0}", i)); } and int[] returnArray = Do.Something() ?? new int[] {}; and ... ?? new int[0] In a NotifyCollectionChangedEventHandler I wanted to apply the Enumerable.Empty like so: foreach (DrawingPoint drawingPoint in e.OldItems ?? Enumerable.Empty<DrawingPoint>()) this.RemovePointMarker(drawingPoint); Note: OldItems is of the type IList And it gives me: Operator '??' cannot be applied to operands of type 'System.Collections.IList' and System.Collections.Generic.IEnumerable<DrawingPoint> However foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[0]) and foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[] {}) works just fine. Why is that? Why does IList ?? T[] work but IList ?? IEnumerable<T> doesn't? When using this expression: a ?? b Then b e...

Detect differences between two strings

I have 2 strings string a = "foo bar"; string b = "bar foo"; and I want to detect the changes from a to b. What characters do I have to change, to get from a to b? I think there must be a iteration over each character and detect if it was added, removed or remained equal. So this is my exprected result 'f' Remove 'o' Remove 'o' Remove ' ' Remove 'b' Equal 'a' Equal 'r' Equal ' ' Add 'f' Add 'o' Add 'o' Add class and enum for the result: public enum Operation { Add,Equal,Remove }; public class Difference { public Operation op { get; set; } public char c { get; set; } } Here is my solution but the "Remove" case is not clear to me how the code has to look like public static List<Difference> CalculateDifferences(string left, string right) { int count = 0; List<Difference> result = new List<Difference>(); foreach (char ch in left) {...

How to round to nearest even integer?

My last goal is always to round to the nearest even integer. For example, the number 1122.5196 I want as result 1122. I have tried this options: Math.Round(1122.5196d, 0, MidpointRounding.ToEven); // result 1123 Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123 At the end, what I would like to get it is always the nearest even intenger. For example: 1122.51 --> 1122 1122.9 --> 1122 (because the nearest int is 1123 but it is odd, and 1122 is nearer than 1124) 1123.0 --> 1124 (the next even value, the next higher even value) I only work with positive numbers. And so on. There are some method that do that or I should to implement my own method? Try this (let's use Math.Round with MidpointRounding.AwayFromZero in order to obtain "next even value" but scaled - 2 factor): double source = 1123.0; // 1124.0 double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2; Demo: double[] tests = new double[] { 1.0, 1123...

String interpolation - what does the @ sign inside the curly braces do?

Consider: string newline = "\r\n"; Console.WriteLine($"Hello without at{newline}how are you?"); Console.WriteLine($"Hello with at{@newline}how are you?"); The output of both lines is identical. The newline is always printed as a newline. Hello without at how are you? Hello with at how are you? So when do I need the at sign inside the curly braces? $"Hello { myValue }" is an interpolated string which was introduced in C#6. In your case this is equivalent to a call to String.Format("Hello {0}", myValue). The verbatim (@) is needed when your variable has the same name as a keyword, which, as far as I know, newline is not. However the following would cause a compiler-error: String.Format("Hello {0}", if) whilst this won´t: String.Format("Hello {0}", @if) Here the verbatim tells the compiler that if is the name of a variable, not the if-keyword. So you don´t need the verbatim in your case, because newline is not a ke...

Find duplicate in array with a memory efficient approach

A is an array of integers. All the values are between 0 to A.Length-1 it means 0 <= A[i] <= A.Length-1 I am supposed to find repeating elements; and if there are several repeating elements, then choose the one that has lower index for the repeated item. for example: a = [3, 4, 2, 5, 2, 3] then result = 2 This was an interview question. I used another array to store items and check when it is repeating. Then it gave me time-out for some test cases. The interviewer advised to only loop over the array only once, and do not create any additional data structure. No need for another data structure. You can use the input itself as a hashset. Every time you see a value, add A.Length to the item that corresponds to that index. As values might have been already incremented, you should look at the value as A[i] mod A.length. If you find an item that is already >= A.length.. you have a repetition. (Remember that the problem states that all items are in the interval [0, A.Length-1]) T...

When should I await my asyncs?

We're currently refactoring sections of our project to be async up and down, yay! Due to our different understanding, me and a colleague (let's call him Jim), have differing opinions about how our async/await code will execute, and which way to write it. Here is the example method Jim wrote: public async Task<HouseModel> GetHouseModel(Guid houseId) { House house = await _houseService.GetHouse(houseId); Task<IEnumerable<Furniture>> furniture = _furnitureService.GetFurnitureForHouse(house); Task<IEnumerable<Appliances>> appliances = _applianceService.GetAppliancesForHouse(house); return _houseModelFactory.MakeHouseModel(await furniture, await appliances); } And the example of how I would write it: public async Task<HouseModel> GetHouseModel(Guid houseId) { House house = await _houseService.GetHouse(houseId); IEnumerable<Furniture> furniture = await _furnitureService.GetFurnitureForHouse(house); IEnumerable<A...

c#中通过静态类中静态字段全局共享实现数据传递

最近在各种语言混着学,感觉自己会不会走火入魔。。。 废话不说了,今天看了winform的一个教程,主要是讲述了对与三个form对象,form1作为主窗口,从里面的button1打开form2,form2中的button2打开form3,然后在form3中的button3中关闭所有表单。这里就出现了一个问题,难道是在form3中也new一个form1对象吗,然后利用form1.close();进行关闭吗,经实验是不行的。 接下来,就看看怎么实现了,前面的两步不用说了,现在看第三步,我们就要想了,怎么样把form1的对象传递给form3呢?