what does this string.format piece of code do? - c#

I have this piece of code in c#:
private static void _constructRow(SqlDataReader reader, system.IO.StreamWriter stwr, bool getColumnName)
{
for (int i = 0; i < reader.FieldCount; i++)
stwr.Writeline(String.Format("<td>{0}</td"), getColumnName ? reader.GetName(i) : reader.GetValue(i).ToString()));
}
I'm trying to understand what the part that start with "getColumnName ?" and ends with ".ToString()" does. I understood that it is a system.object type, but I have no idea what it specifically does or how it works.
I want that because of this: "reader" had multiple rows in it, and I want to writeline only specific rows.
If anyone can help me on either of those, I'd be grateful.

This is a conditional operator. It says if getColumnName is true, then use reader.GetName(i) otherwise use reader.GetValue(i).ToString()
The format is this:
ThingToCheck ? UseIfCheckIsTrue : UseIfCheckIsFalse
In the code, it looks like getColumnName is true for the header row, so it's outputting the column name and called again for all other rows using false, to output the values.

The function iterates over all columns in the data reader, then for each one:
If getColumnName returns true, it outputs the name of the column between the <td> tags, otherwise the value of the data.
To de-construct further:
reader.GetName(i) - this returns the name of the column
reader.GetValue(i).ToString() - this returns the value of the column as a string
getColumnName - a function the will return true if a column name can be gotten
?: - the conditional operator. If the expression before the ? is true, the expression to the left of the : is used, otherwise the one on the right
String.Format("<td>{0}</td", arg) - this will output "<td>arg</td>" (btw - your code is wrong, the ) should not be just after the first string)

That is called a conditional operator.
The argument getColumnName is evaluated and if true, the first argument after the ? is returned, if false, the second.
So, if getColumnName==true, you are going to see <td>NAME</td> else <td>Value</td>
Make sense?

It is like following
if (getColumnName == true)
{
reader.GetName(i); // GetName is string so no need to convert this in string I.E ToString()
}
else
{
reader.GetValue(i).ToString(); // GetValue returns object so this needs to convert in string using .ToString()
}
Because getColumnName is of bool type so no need to test it like
If (getColumnName == true)
You can write this as
If (getColumnName)
String.Format(string, method)
And String.Format method replaces items in specified string with given object, this method has two arguments first one is string and second is object.
for example
string.Format("Question number {0} is answered by {1} {2}", 11, "Adam", "Yesterday");
The out put will be
Question number 11 is answered by Adam Yesterday
As you can see {0} is replaced with 11 and {1} is replaced with Adam and {2} is replaced with Yesterday.
you can read more about this here

this is ternary operator, used for adhoc constitution of if else block.

Related

How TryParse method works?

I have the following code.
using System;
class program
{
static void Main()
{
string StrNumber = "100TG";
int result = 0;
bool IsConversionSuccessful = int.TryParse(StrNumber, out result);
if (IsConversionSuccessful)
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Invalid");
}
}
}
I know that TryParse method tries to convert StrNumber(100TG) into an integer.
And if it succeeds, it's going to save converted value into a result variable and return true for boolean.
And if it fails, a result value will remain as 0 and it will return false for boolean.
My question is that no matter what kind of boolean value IsConversionSuccessful variable gets, wouldn't "if(IsConversionSuccessful)" get activated? Am I misunderstanding TryParse Method?
If IsConversionSuccessful gets to be false, then the condition if(IsConverstionSuccessful) evaluates to if(false). Hence, the body of that if does not execute.
The TryParse method does not determine the execution of the next line in your program. It simply tells you whether the conversion from string to int was successful or not by returning a boolean value.
The lines following TryParse is up to you.
As you clearly have pointed out,
bool IsConversionSuccessful = int.TryParse(StrNumber, out result);
Will set IsConversionSuccessful to true/false based on how the method parsed the number.
If statements in themself evaluate something and always get a boolean answer, true or false. This is because if statements act like binary branch trees. They work like this:
When you evaluate if(A), which in your case is
if (IsConversionSuccessful)
The processor decides on a path to take and execution after that depends on the decision the processor made. Note that even excluding the else branch, an empty else branch simply points back to the "..." that comes after the if statement.

initialised string seems to contain string.Empty [duplicate]

This question already has answers here:
Why does "abcd".StartsWith("") return true?
(11 answers)
Closed 9 years ago.
I jumped into this accidentally and have no clue as to why this is happening
string sample = "Hello World";
if (sample.Contains(string.Empty))
{
Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty));
Console.WriteLine(sample.LastIndexOf(string.Empty));
Console.WriteLine(sample.Length);
}
Output
This contains an empty part ? at position 0
10
11
I am happy with the last part, but i have no idea why this is evaluated true. Even Indexof and LastIndexOf have separate values.
Could anyone help me out on why is this so?
EDIT
I believe this is a bit relevant to my question and would be also helpful to those who stumble upon this question.
See this SO link: Why does "abcd".StartsWith("") return true?
From msdn for IndexOf
If value is String.Empty, the return value is 0.
For LastIndexOf
If value is String.Empty, the return value is the last index position in this instance.
For Contains
true if the value parameter occurs within this string, or if value is the empty string ("");
Question: Does the string "Hello World" contain String.Empty?
Answer: Yes.
Every possible string contains String.Empty, so your test is correctly returning true.
If you are trying to test if your string is empty, then the following code is what you want
if (string.IsNullOrEmpty(sample))
{
}
This is documented in the String.Contains Method:
Return Value
Type: System.Boolean
true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false.
And in String.IndexOf Method
If value is String.Empty, the return value is 0.
And in LastIndexOf Method
If value is String.Empty, the return value is the last index position in this instance.

Why use out keyword instead of assignment in c#?

I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:
public void Function1(int input, out int output)
{
output = input * 5;
}
public int Function2(int input)
{
return input * 5;
}
...
int i;
int j;
Function1(5, out i);
j = Function2(5);
Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?
Usually out is used for a method that returns something else, but you still need to get a different value from the method.
A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.
int myOutVar;
if (Int32.TryParse("2", out myOutVar))
{
//do something with the int
}else{
//Parsing failed, show a message
}
The out / ref keywords in C# should only be used when you need to return multiple values. Even then you should first consider using a container type (such as Tuple) to return multiple values before you revert to out / ref. Whenever you're returning a single value it should just be returned.
A lot of times, using out can help by giving you a slight performance gain.
Consider the TryGetValue method on IDictionary (say myDictionary is an IDictionary<string, string>) Rather than doing this:
string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
value = myDictionary["foo"];
}
Both ContainsKey and the indexer need to look up the key in the dictionary, but you can avoid this double-lookup on the positive case by going:
string value;
if (!myDictionary.TryGetValue("foo", out value))
{
value = String.Empty;
}
IMO, that's a decent reason for using out parameters.
Unfortunately we cannot do something like below in C#:
a,b = func(x,y,z);
something that we do in Python or other languages. out kind of overcomes that.
F# has overcome this with tuples I believe.
PS: Returning multiple values from a function might not be good always. Tiny types are good most of the times - http://www.martinfowler.com/bliki/DataClump.html
For example, Int32.TryParse returns boolean if it parsed correctly and with the out parameter changes the value. If the parsed value is 0 and it returns true it means the value you sent to parse was 0. If it returns false then the parser failed.
Some of it is for clarity. Take the TryParse() methods, like
Int32.TryParse("3", out myInt);
This returns a bool that indicates whether the string was able to be parsed into an int.
If you just had
Int32.TryParse("3", myInt);
What happens when that's called? Is myInt assigned? Does TryParse return an int?
It's not readily apparent. But if I have an out parameter, then I know that the value is getting assigned, and that the return is something else.
Basically you do something like (my database read)
if (ReadSingle<UserRecord>(cmd, out user))
Cache.Insert(cacheId, user, null,
DateTime.MaxValue, TimeSpan.FromMinutes(3));
Or else you do something like:
user = ReadSingle<UserRecord>(cmd);
if(null != user)
// Cache.Insert ...
It simplifies the code a little to use a boolean result (that a record was read from the database) and get the actual record into the variable via the out keyword.

Difference between Forward and Reverse Comparison in C#

this is related to comparing values in C#.
basically by default, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks
This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null or non-0 would be treated as true, otherwise it was equivalent to false. This meant that any assignation of a constant would always be true.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5 is the result of 2+3, myInt = 5 also returns 5.
Because of this, it was recommended that you check the variable against the constant. The null example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i is assigned the value of 1, which then returns the value of the assignment, 1, to the if statement. This is equivalent to true, and the if condition matches.
If you were to attempt to assign i to the constant 1, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }, as a string has... two ... default values from a semantic perspective.
Reverse comparison protects you from errors, when you use == (compare) instead of = (assign). But complier also warns you if you do this.

Convert.ToBoolean("1") throws System.Format Exception in C#

Why does
Convert.ToBoolean("1")
throw a System.FormatException?
How should I proceed with this conversion?
Yes, this is as documented:
[throws] FormatException [if] value is not equal to TrueString or FalseString.
TrueString is "True" and FalseString is "False".
If you want to detect whether a string is "1" or not, use this code:
bool foo = text == "1";
Depends on what you want. Perhaps
var result = Convert.ToInt32(yourstirng) != 0
assuming any number but 0 is true. Otherwise a simple comparison would work.
var result = yourstirng == "1"
The parameter must be equal to either Boolean.TrueString or Boolean.FalseString. The values of these strings are "True" and "False", respectively. See MSDN.
The string value "1" is obviously not equal to "True" or "False".
The problem is, that youre giving a String here, not a number. It cant convert the String "1" to true, but the int 1.
Convert.ToBoolean(1);
should work.
When converting to Boolean it is best to use your own routine, where you handle all cases. .net Convert.ToBoolean isn't a practical routine, it is one of those function where you have to explain why it doesn't work.
I know this is old, but in case someone searches... simply do this:
Convert.ToBoolean(Convert.ToInt16("1")) works just fine. Not pretty, but needs be.
Another solution is to use an Extension Method on the string object. I used this technique in a case where I had to parse CSV files that had different strings that had to be converted to boolean values depending on their source and format.
public static class StringExtensions
{
public static bool ToBool(this string value,string trueValue)
{
if (value == trueValue)
{
return true;
}
else
{
return false;
}
}
}
This would be called like so...
MyProperty = CsvColumn[6].ToBool("1");
If you want, the truevalue parameter could be a string array if you needed to compare multiple values (like n/a, na, none) and you could add in false values if you want to further restrict it or use nullable types.

Categories

Resources