object.ReferenceEquals behave differently [duplicate] - c#

This question already has answers here:
Two different "strings" are the same object instance?
(3 answers)
Closed 6 years ago.
string x = "alok b";
string y = "alok b";
string z = "alok";
//y += x.Replace(y, string.Empty);
z += " b";
Console.WriteLine(object.ReferenceEquals(x,y));
Console.WriteLine(object.ReferenceEquals(y, z));
How is first line is printing true and second false?
and changing to below statement is printing true.
Console.WriteLine(object.ReferenceEquals(y,string.Intern(z)));

It's called string interning.

When you create a string it creates an object (x).
when you create y, you just point to it"again", it points to the same one (has it).
When you create Z, and the do the += it creates a NEW one altogether, hence, it won't match the address in the memory for the previous one.

Related

Correct way to change value in List<int> / array [duplicate]

This question already has answers here:
i = i++ doesn't increment i. Why? [duplicate]
(4 answers)
Closed 1 year ago.
Suppose the List/array
List<int> a = new List<int>(){1,2,3,4,5};
int []a = new int[]{1,2,3,4,5};
And I want to change the value at index 2, whats the correct way?
a[2]++; or a[2] = a[2]++;
Please explain the answer.
The result of a[2] = a[2]++ will be a[2], in this case 3.
The postfix increment a[2]++ will change the value of a[2] after the line in which it appears has finished.
If you want to change the value, then a[2]++ or a[2] = ++a[2] are valid.
The correct way is the first one:
A[2]++;
The second one also works but it does more work than necessary. It is equivalent to the following code:
a[2] = a[2]; // useless
a[2]++;
The suffix ++ operator (as in x++) applies after the line in which it appears has finished executing. The prefix ++ operator (as in ++x) first modifies the element and then uses the value.
I suggest you read the documentation about the "increment operator":
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator-

lambda functions have strange behaviors in loops, how to fix? [duplicate]

This question already has answers here:
Can someone explain "access to modified closure" in C# in simple terms? [duplicate]
(1 answer)
Captured variable in a loop in C#
(10 answers)
Closed 5 years ago.
I get a really weird behavior with this piece of code
for (int i = 0; i < 2; ++i)
optionContent.GetChild(i).GetComponent<Button>().onClick.AddListener(() => SetOption(i, true));
The weird behavior is that all listeners gets attached the function SetOption(2, true)
I think the 2 comes from the fact that at the end of the for loop, i is set to 2, but still, why is this the behavior and is there a way to get around this?
Edit:
I played around for a bit and I think the problem is that delegates store variable references as references, not values
int x = 0;
Action a = delegate { int b = x; Console.WriteLine(b); };
x = 10;
a();
The above code will print 10, instead of 0. How do I make it to use the value 0?

C# increment a variable and convert to string on one line [duplicate]

This question already has answers here:
Pre- & Post Increment in C#
(6 answers)
Closed 5 years ago.
Simple request -- does anybody know a way to consolidate this to one line:
edit - I was NOT confused about pre vs post increment operators. The question I posted should have worked, I honestly do not know what happened. somewhere between VS and SO I fixed it.
startingMask++;
string mask2 = startingMask.ToString().PadLeft(3, '0');
Something like
string mask2 = (startingMask++).ToString().PadLeft(3, '0');
edit -- Alright -- chill out -- :)
Here is the final full solution, I should have provided more info in my first question, I was just looking for a nudge in the right direction (the number needed and starting number will be changing via a database pull at some point):
int startingMask = 76;
int numberNumberNeeded = 10;
List<string> masks = new List<string>();
while (numberNumberNeeded > 0)
{
string newMask = (startingMask++).ToString().PadLeft(3, '0');
masks.Add(newMask);
numberNumberNeeded--;
}
string mask2 = (++startingMask).ToString().PadLeft(3, '0');
Postfix ++ startingMask++ first take value and then increment value
Sufix ++ ++startingMask first increment value and then take value

Float calculation showing difference. Positive showing negative? [duplicate]

This question already has answers here:
Always return positive value
(9 answers)
Closed 5 years ago.
I am calculating the difference between two numbers. If the calculation ends up being 5 - 10, it equals to "-5". If this is the case I need results to display/equal to "+5" , with the "+" sign.
I basically need reverse. So same if 10 - 5 quals to "5" I need it to display as "+5"
Code below I am using:
float rowresults = ROW1 - ROW2;
Textbox.text = rowresults.ToString();
Math.Abs is what you are looking for:
float rowresults = Math.Abs(ROW1 - ROW2);
And to add the "+"-sign to the front of the text (without changing your elsewise existing behaviour):
Textbox.text = "+" + rowresults.ToString();

Read 3 variables on the same line C# [duplicate]

This question already has answers here:
Is there an equivalent to 'sscanf()' in .NET?
(8 answers)
Closed 6 years ago.
I have a question. I work on a console application and I would like Read 3 variable on the same line.
With the language C we can write this
int a;
string b;
int c;
scanf("%d %s %d", &a, &b, &c);
When I start the program I write : 1+1 on the same line and a = 1 b = "+" c = 1
How can I make the same in C# with console.readline() ?
Thank you in advance,
Nico
This answer is modified from reading two integers in one line using C#. So you can do it several ways as described in this answer, but i would suggest like:
//Read line, and split it by whitespace into an array of strings
string[] scanf= Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(scanf[0]);
//Parse element 1
string b = scanf[1];
//Parse element 2
int c = int.Parse(scanf[2]);
I would suggest following the link as there is more ways described.
No, there is no equivalent, but you can easily create one:
void Scanf(out string[] values)
{
values = Console.ReadLine().Split();
}
However you have to parse every argument in your calling code:
int a;
string b;
int c;
string[] r;
scanf(out r);
int.TryParse(r[0], out a);
b = r[1];
int.TryParse(r[2], out c);
If you want to verify the format of the strings and numbers also you probably need a regex:
var r = new Regex("(\\d+) (\\S+) (\\d+)");
var values = r.Matches(Console.ReadLine())[0];
Now again you need to parse:
int.TryParse(values.Groups[1], out a);
b = values.Groups[2];
int.TryParse(values.Groups[3], out c);
Remember that the first group within a regex allways contains the complete match-string, so the first capturing group has index one.

Categories