I am trying to understand what is happening in this variable assignment.
num = forward.Data.Key >= key ? 1 : 0;
In particular this part >= key ? 1 : 0
To help out forward is a LinkedListCell<KeyValuePair<int, double>> forward = _data.Next;
key is an int parameter being passed into the method.
Also it is a program written in C#
That's the ternary operator. It takes a boolean expression, and returns one of two values depending on the result of that expression. You get it in a number of languages.
It's equivalent to:
if( forward.Data.Key >= key ) {
num = 1;
}
else {
num = 0;
}
It is called ternary conditional operator. (or the short If-Else statement)
value = condition ? truePart : falsePart;
The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison.
from MSDN,
int input = Convert.ToInt32(Console.ReadLine());
string classify;
// if-else construction.
if (input < 0)
classify = "negative";
else
classify = "positive";
// ?: conditional operator.
classify = (input < 0) ? "negative" : "positive";
Related
I was reading through some code on Github recently and i came across the following line,
if (((tmp = rx.IndexOf("<")) >= 0) && (rx.IndexOf(">") > tmp ))
specifically the
(tmp = rx.IndexOf("<") >= 0)
And the immediate use of the tmp variable in a comparison in the same line in the next part of the if statement
(rx.IndexOf(">") > tmp )
in which a variable is being set by a string,indexOf() method, and then the 'assignment statement itself' is being evaluated with a greater-or-equal-to equality operator.
At first i thought this was a typo, but on evaluating the code via a simple console app, i found it to be valid, and a great shortcut.
The question is "What is the technical term for this?" as i could find no explanation in various C# help sites.
An example console app to demonstrate how the statement was used.
public static void Main()
{
// first test - the actual code I found in gitHub
int tmp;
int tmp2;
string rx = " < test>";
// the below line is the subject of the question.
if (((tmp = rx.IndexOf("<")) >= 0) && (rx.IndexOf(">") > tmp )){
Console.WriteLine("The Close brace is after the opening brace!");
}
// additional test
int r;
Console.WriteLine(r = 25 + 3);
Console.WriteLine(r);
// and another
int w = -1;
Console.WriteLine(" The index of '<' is greater than 0 : " + _
((w = rx.IndexOf("<")) > 0).ToString() + _
" and the value of w is " + w.ToString());
}
The output of the above code is below.
Again , I understand the code works, I would like to know what is this called technically?
The Close brace is after the opening brace!
28
28
The index of '<' is greater than 0 : True and the value of w is 2
There is no "technical term".
It's an assignment, and a assignment can act as expression or a statement.
It's a statement that has a value; Or an Expression where the result value can be ignored. (Unlike x+y, the Result is not allowed to be ignored)
It's the same as the prefix and postfix operators i++;
It will look less like "inline" in a line like x = y = z;
However, it's not often used, cause it's less readable, as you just proofed.
And in your case, assigning a value and using the value in the same expression tree
highly depends on evaluation order, which is well defined, but who knows it by heart ?
This style of writing will safe you a line of code (by making one line longer)
but it will never save you any operation, hence not cause any performance.
So Read it, Understand it, but better don't use it frequent.
This is just a consequence of assignment being an expression. It is defined in the C# specification:
7.17.1 Simple Assignment
The = operator is called the simple assignment operator.
The result of a simple assignment expression is the value assigned to
the left operand. The result has the same type as the left operand and
is always classified as a value.
So the value of
tmp = rx.IndexOf("<")
is the value assigned to tmp which is rx.IndexOf("<"). This value is then compared to 0 in the outer expression.
I want to get result of a value with if condition.
i have get some value in xml file.
now what I want is
if I have a variable "a" here i have assigned some values by using dataset.
and i have another variable "b" is assigned value from xml file.
for example
int a=25;
string b=">10"
now I want to check the condition if condition with out ">" because the symbol present in b variable. I dont know how to check this condition can anybody explain me how to acheive this.
I tried like this but not working
if(a+b)
You can use the DataTable.Compute-"trick" to evaulate such expressions:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
What is supported you can read at the DataColumn.Expression remarks.
if the condition is 1!=10, how to use not equal in this code .this
condition is not working what should i do.
As the documentation tells you that is not valid syntax, you have to use <> (look at operators). So a simple approach would be either to use <> in the first place or replace them:
b = b.Replace("!=", "<>");
You can have some function to remove non numeric characters:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
If its always a number with a symbol then:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
And considering your comment for comparison you can do:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
Of course you may need only one of < = > or you may need to have separate if conditions for each, what ever suits your needs, but I just wanted to give the idea.
I tried like this
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
similarly all the symbols
First separate symbol from b:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
Now use switch to get operation for symbol and compare:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
EDIT: Changed symbol declaration to avoid error: "cannot implicit convert type char to string"
My code was giving me Index out of Range exception for a certain input. Below is the problematic code:
string[] snippetElements = magic_string.Split('^');
string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";
For that particular input, array snippetElements had only one element in it, hence while trying to index 10th and 11th element, I got the exception.
For now, I have introduced the following check:
if (snippetElements.Length >= 11)
{
string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";
}
Can someone suggest a better way to write this check. Somehow the number 11 is not looking good in the code.
Yes this is an old post, but still helpful. You could use this which I think is cleaner:
string a = snippetElements.ElementAtOrDefault(10) ?? "hello";
string b = snippetElements.ElementAtOrDefault(11) ?? "world";
Can someone suggest a better way to write this check. Somehow the
number 11 is not looking good in the code.
Well you are accessing the element with 11 index, if you have that index in your variable then you can use that in your check, otherwise 11 is fine in your check. Your check should be if(index < snippetElements.Length)
Something like:
int index = 11;
if(index < snippetElements.Length)
{
string b = snippetElements[index] == null ? "" : "world";
}
snippetElements[11] is the 12th element.
if (snippetElements.Length >= 12)
As long your are actually using the [10] and [11] indexes it doesn't look wrong to use the 12 in the if statement.
You can generalize the problem to an extension method like this:
public static class ArrayExtensions
{
public static bool TryIndex<T>(this T[] array, int index, out T result)
{
index = Math.Abs(index);
result = default(T);
bool success = false;
if (array != null && index < array.Length)
{
result = (T)array.GetValue(index);
success = true;
}
return success;
}
}
And convert your code to:
string[] snippetElements = magic_string.Split('^');
string a = null;
string b = null;
if (snippetElements.TryIndex(10, out a) && snippetElements.TryIndex(11, out b))
{
}
Or, more like your source code and using the TryIndex(...) extension method:
string[] snippetElements = magic_string.Split('^');
string a = null;
string b = null;
snippetElements.TryIndex(10, out a);
snippetElements.TryIndex(11, out b);
a = a ?? "hello"; // Null coalesence ?? operator is great!
b = b ?? "world";
It makes the array indexed access safer since your code won't never throw ArgumentOutOfRangeException.
Note that this extension method will work for any kind of array, regardless of its type! Either if its a value type (int, byte...) or a reference type (string, your own classes...).
The logic here is wrong.
If your Split method produces less than 12 elements your indexing on the array snippetElements could go only from zero to (Length - 1) of the array.
In that case there aren't elements at index 10 or 11. And, in any case, if the snippetElement.Lenght is equal or greater than 12, then the elements in the array can't be null. Or they contain a string or they will be empty strings.
You could just write
string a = snippetElements.Length >= 12 ? "hello" : string.Empty;
string b = snippetElements.Length >= 12 ? "world" : string.Empty;
It might be late now, but for any one else who's having the same problem, that's how I solved it. I usually use this logic inside a for loop.
int index = 10;
string a = (index < snippetElements?.Length) ? snippetElements[index] : string.Empty;
snippetElements?.Length checks if snippetElements is not empty then it calls its Length property. Accessing Length property of an empty array results in an exception.
snippetElements[index] (you could replace this with "hello" as in your example) is accessed only if the index is in the bound of an array. Otherwise, it assigns String.Empty to a.
// Example bool is true
bool t = true;
// Convert bool to int
int i = t ? 1 : 0;
Console.WriteLine(i); // 1
This converts false to 0 and true to 1, can someone explain to me how the t ? 1 : 0 works?
Look at the Ternary Operator.
int i = t ? 1 : 0;
Equates to:
if(t)
{
i = 1;
}
else
{
i = 0;
}
This syntax can be found in a variety of languages, even javascript.
Think of it like an English sentence if you swap the colon for "otherwise":
bool isItRaining = false;
int layersOfClothing = isItRaining? 2 otherwise 1;
It's the C# Conditional Operator.
i = does t == true? if yes, then assign 1, otherwise assign 0.
Can also be written as:
if (t == true)
t = 1;
else
t = 0;
or
if (t)
t = 1;
else
t = 0;
Since t is true, it prints 1.
if t equels true then i=1 else i=0
ternary operator
bool t= true;
int i;
if(t)
{
i=1;
}
else
{
i=0;
}
For more look ?: Operator
(? *) this is conditional operator.
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form
condition ? first_expression : second_expression;
here in you case (true?1:0 ) since the condition is true ,which is certainly setting value of i to 1.
I believe that internally the compiler will inline the statement to the equivalent of:
Console.WriteLine(Convert.ToInt32(t));
This Convert.x method checks to see if the passed parameter is true return 0 if it isn't.
I want to check if two string are of the same length. I tried the following, but it doesn't work.
string passnew = "1233";
string passcnfrm = "1234";
if((passnew.Length&&passcnfrm.Length)>6 ||(passnew.Length&&passcnfrm.Length)<15)
{
// ...
}
Why does it not work? What do I need to change?
if(passnew.Length == passcnfrm.Length &&
passnew.Length > 6 && passnew.Length < 15)
{
// do stuff
}
You are missing some basic syntax lessons. What you write inside of these brackets are conditions. We have unary operators (operating on one thing), binary operators (two) and one tertiary operator (forget about that one).
You cannot construct something like your "boundary test" with those easily.
A possible way:
(passnew.Length > 6) && (passcnfrm.Length > 6)
But you aren't testing if the length is equal anyway, even if you could use a syntax like that. You seem to want to compare if both are longer than 6 chars and shorter than 15 chars. One at 7 and one at 14 would satisfy both conditions..
if(passnew.Length == passcnfrm.Length &&
(passnew.Length < 15 && passnew.Length > 6))
{
// ...
}
Checks both are same length, and either one is more than 6 and less than 15 characters long.
that would be:
if(passcnfrm.Length.Equals(passnew.Length))
{
//do stuff
}
A probably better way to do it is:
if (( passnew != null && passcnfrm != null )
( passnew == passcnfrm )
&& ( passnew.Length > 6 && passnew.Length < 15 ))
{
// do stuff
}
Hides the length check inside the equality check which you'll probably need, it isn't in your question but the variable names make it pretty clear you're doing a password change function there. I added the null check to make sure the length checks don't throw a NullReferenceException, not needed in the example because you assign both manually, but might save some trouble if you're going to convert this to a method later on.
You can use like this:
if (s.Contains(s1[i]))
or:
boolean equalsIgnoreCase(String anotherString);
or use this method:
public static int occurrence(string [] a, string a2)
{
int occ = 0;
for (int i = 0; i < a.Length;i++ )
{
if(a[i].Equals(a2))
{
occ++;
}
}
return occ;
}