Behaviour of C# code [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Explaining post-increment in C#
Consider the following C# code:-
int i = 2;
i = i++;
Console.WriteLine(i);
I am getting the output as 2. Why there is no effect of i = i++?

Depending on where you put the +-operators, the value assigned is incremented before or after:
i = ++i;
This way i is counted up before assigned.
i = i++;
This way i is counted up after assigned.

Because the = operator takes precedence first.
MSDN: Operator precedence and associativity.
Try this one:
int i = 2;
i = ++i; // or write just ++i;
Console.WriteLine(i);

Related

why this gives me an scope error in a for loop variable [duplicate]

This question already has answers here:
C# local variable scope [duplicate]
(5 answers)
Closed 2 years ago.
So I was doing a simple for loop and suddenly i got an scope error. if I change the i in int i = 100 it dissapears but I just want to understand why this happens.
The error appears int the for(int i = 0; i<10; i++)
A local parameter called 'i' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
class Class1
{
static void Hi()
{
for(int i = 0; i<10; i++)
{
//do something
}
int i = 100;
}
}
The declaration of int i = 100; is considered to be enclosing the for loop (regardless of whether it's not at the top of the method), so you cannot use the same name variable as one that appears in a block that contains your block.

Why is counter going further than it should? [duplicate]

This question already has answers here:
Lambda variable capture in loop - what happens here? [duplicate]
(3 answers)
Starting tasks inside a loop: how to pass values that can be changed inside the loop? [duplicate]
(1 answer)
Captured variable in a loop in C#
(10 answers)
Closed 2 years ago.
I have asynchronous method which for purpose of this question can be shortened to syntax like this:
public async Task<int> PositiveParallelAnticipation()
{
//some operations
List<List<MatchResult>> ranges = SplitRange(possibilityList, 4);
var tasks = new List<Task<int>>();
for (int i = 0; i < ranges.Count; i++)
{
//some more operations
//!here is the problem!
tasks.Add(Task.Run(() => PositiveAnticipationLoop(new Team(target), currWorkingTeamList, currworkingMatchList, startingPossibility, ranges[i])));
}
int[] results = await Task.WhenAll(tasks);
return results.Max();
}
And when I run it in debug mode it's all good but when I do it without debugging it throws error like this (when trying to get ranges[i]):
Index was outside the bounds of the array."
What am I missing? And btw I don't mutate ranges list and don't increment or decrement i in any operation which is not included here.

Remove file extension from each item in the array c# [duplicate]

This question already has answers here:
Remove file extension from a file name string
(13 answers)
Closed 4 years ago.
I have an array with items having names with .txt.
I want to remove the extension. The following code is not working.
var xx = filenames.ForEach(x =>
{
int fileExtPos = x.LastIndexOf(".");
if (fileExtPos >= 0)
x = x.Substring(0, fileExtPos);
});
Can anyone help what am i doing wrong here?
Thanks
There is a build in method GetFileNameWithoutExtension() which could be used. That's the common way to handle this.
var result = filenames.Select(System.IO.Path.GetFileNameWithoutExtension);
You error appears here var xx = filenames.ForEach because ForEach has no return value (void) which could be assigned to var xx.

c# Why does this for loop with a task.run prints more than 10 times? [duplicate]

This question already has answers here:
How can I capture the value of an outer variable inside a lambda expression?
(4 answers)
Closed 6 years ago.
What is going on here? This loop most of the time just prints this:
10101010101010101010
sometimes this:
51010101010101010101
and when i debug it, it prints in order
0123456789
class Program
{
static void Main (string[] args)
{
for ( int i = 0; i < 10; i++)
{
Task.Run(( ) => Console.Write(i));
}
Console.Read();
}
}
If you have ReSharper installed it puts a little squiggle underneath the i:
with the note:
Access to modified closure
The JetBrains site gives this explanation:
This may appear to be correct but, in actual fact, only the last value of str variable will be used whenever any button is clicked. The reason for this is that foreach unrolls into a while loop, but the iteration variable is defined outside this loop. This means that by the time you show the message box, the value of str may have already been iterated to the last value in the strings collection.
(obviously their example uses a string not an int).
It "works" under debug because other things are going on and the code isn't being executed the same as it would in release.
The solution is to use a local variable:
for ( int i = 0; i < 10; i++)
{
int local = i;
Task.Run(( ) => Console.Write(local));
}
But even then it's not guaranteed to execute in the order you expect. I just tested this and got he result:
0436215897
So each value was processed, but in indeterminate order.

C# variable declaring [duplicate]

This question already has answers here:
Variable scope confusion in C#
(4 answers)
Closed 9 years ago.
Is there any practical difference (speed, memory) between these two ways of declaring (introducing) variables? Which one is the better way?
Example 1:
for (int i = 0; i < myObjects.Length; i++)
{
MyObject m = myObjects[i];
}
Example 2:
MyObject m = null;
for (int i = 0; i < myObjects.Length; i++)
{
m = myObjects[i];
}
Thanks.
Example 1 makes it so that m is only "alive", in memory, within the scope of the for loop.
Example 2 makes it so that m stays occupying memory after the for loop finishes executing.
I would go with example 1, this is why:
Declaring variables inside or outside of a loop (I won't really tell you, in detail, to force you to read the link.)
Performance-wise both are compiled to the same IL, so there's no difference.
The first one is better because you are meaning to have a new object in each iteration. Also there is no need to have an object if the loop condition fails

Categories

Resources