One of my friend had an interview with a company, and he told me it didn't go well as they asked some detail questions in C#. I asked him to tell me a few of the questions. One question was interesting i guess, cause i think it is so simple that nobody will ask in the interviews. Of course guess what? my friend didn't give the right answer :).
It is a small sample code, asking what is wrong this with code. here is the code:
string name=”john Doe”;
if(name.Length)
{
Console.WriteLine("name is greater than 0 characters");
}
Maybe my friend was very anxious during the interview, as it is very difficult to get a job nowadays (economic crisis really hurt a lot), but i think any decent c# programmer should see the problem right away because it is a compiler time error. It is difficult to catch the runtime errors, but compile time errors? You just need to compile your code a good number of times i guess :) Anyways let’s go back our question. If you read the C# reference for if keyword, you will see that inside the parentheses right after if; you have to write an expression that can be implicitly converted to a bool. Integer types can’t be converted to bool implicitly, and you have to write an expression that will evaluate a boolean value .
In the code if(name.Length) , the expression name.Length returns an integer not a bool, so if want to fix this code :
string name=”john Doe”;
if(name.Length>0)
{
Console.WriteLine("name is greater than 0 characters");
}
Also checkout String.IsEmptyOrNull()
let the force help you