.Net, C#, C# 7

Out Parameters

I’m so happy to see this new, very simple improvement in C# 7.  You probably have to write the code similar to the one below many times:

   int outNum;
   var tryParse = int.TryParse("5", out outNum);

In C# 6 and earlier versions, we had to use two statements.  One to declare a variable and then to call int..TryParse method.  I take pride of having my classes and methods as small as possible. I can save a line with this new feature, no need to declare a variable.

   var tryParse = int.TryParse("5", out int outNum);

In some cases you don’t care about the out variable at all. You just want to know if you can parse string to int or not. In this case, use a single underscore instead the variable name to create a discard.

   if (int.TryParse("5", out _))
   {
      // Some logic
   }

Because we don’t need the declaration of the variable, we can implement a method with an expression body:

   static int ParseOrMyDefalt(string text) =>
      int.TryParse(text, out int value) ? value : 5;

That’s basically it about new out parameter feature. Once again I’m very happy that I don’t need to deal with annoying variable declaration statement.

Advertisements
.Net, C#, C# 7

Underscore Separators

Another new feature of C# 7 is underscore separators.  Now you can put underscore anywhere inside any numeric literal to make long numbers more readable.  And I mean any, you can put it inside regular integer, binary, hex, decimal and many other numeric literal.

In the statement bellow it’s hard to see how many millions / billions the numeric value has.

int milesFromEarthToSun = 92960000;

We can improve it by putting some separators.

int milesFromEarthToSun = 92_960_000;

With new syntax we can clearly see how many million miles from Earth to Sun.

However, you also can misuse this feature and make code less readable. Unfortunately this example is valid:

int loooooongTen = 1___________0;

This new feature plays nicely with another C# 7 feature (binary literal)

   int readableBits = 0b0010_1111_0000_1111;

When using this feature, you need to be aware of some restrictions.  All examples below are invalid:

  • You can’t prepend the literal with an underscore
    int invalidNumber = _2;
  • You can’t add an underscore to the end of the literal
    int invalidNumber = 2_;
  • You can’t insert an underscore before or after the period in a floating point literal
    
   float invalidFloatNumber = 23_.15f;
   decimal invalidDecimalNumber = 23._15m;
  • You can’t put an underscore after the base specifier (0x or 0b) or before the literal suffix
    
   byte invalidHexByte = 0x_A;
   byte invalidBitByte = 0b_1010;
   decimal invalidDecimalNumber = 23.15_m;

I disagree that we are not allowed to put underscore after the base specifier. I wish I could use something like this:

   int whishToBeValidBits = 0b_0010_1111_0000_1111;
.Net, C#, C# 7

Binary Literals

One of the new feature that comes with C# 7 is binary literals.  We had hex digit literal for a long time 0x or 0X prefix.

int hexNum = 0xA; // Prints 10

With C# 7 we now can represent a number in binary format.  To represent number in binary (bit) format you just need to prefix it with 0b or 0B.

int bitNum = 0b1010; // Prints 10

So why do need to know about this syntactic sugar?

  • If you read a code where this syntax is used, you need to understand it.
  • For bitmasks.
  • When implementing protocol with specific bit patterns.

We also can use it in enum.  Some people might agree that it’s more readable. Before C#7 our enum Colors would looks something like that:

enum Colors
{
   Black = 1,
   Red = 2,
   Blue = 4,
   Green = 128
}

That’s how it looks using binary literals:

enum Colors
{
   Black = 0b0001,
   Red = 0b0010,
   Blue = 0b0100,
   Green = 0b10000000
}

I myself probably would use binary literals only if I have to work with bitmask. However, it’s nice to have an extra option.

byte decByte = 60;
byte hexByte = 0x3C;
byte bitByte = 0b00111100;

The last thing I want to mention is that using binary literals doesn’t affect performance at all.

C#

Capitalize only first character. (C#)

Once in a while, you may need need to capitalize only the first character of a word. Like everything else in programming, there’s more than one way to solve this problem. In this post, I’m going to explore three different ways to capitalize the first letter of a word, and then let you know which one I prefer.

1. String manipulation solution.
private string UpperFirst(string text)
{
return char.ToUpper(text[0]) +
((text.Length > 1) ? text.Substring(1).ToLower() : string.Empty);
}

 

This solution is straightforward. First, capitalize the initial character of the text, and then append the rest. Next, we test if our text has more than 1 character. If this is text with multiple characters, we convert the rest of the text to lowercase, in case there are any uppercase letters.

2. LINQ solution.
private string UpperFirst(string format)
{
return format.First().ToString().ToUpper() +
String.Join("", format.Skip(1)).ToLower();
}

 

LINQ solution is also easy to follow and understand. We get the first character, and then we convert it to String (because the char type doesn’t have instance implementation of ToUpper()). Then, like in the previous solution, we append the rest of text.

3. TextInfo.ToTitleCase solution.
private string UpperFirst(string text)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
}

 

This solution is taking advantage of the ToTitleCase method. It looks simple, but it’s not exactly like our two previous solutions. The problem with this solution is that it’s going to capitalize every word in the text.  For example: if your text has the value “hello world”, the result of this solution will be “Hello World” and not “Hello world” as in the two earlier examples. If you need to capitalize every word in your text, use this solution. Otherwise, use one of the earlier solutions.

The best solution for me.

Personally, the 1st solution looks the best. There are two reasons why I think solution #1 is the best:

  1. I believe it’s easier to read, but readability is very subjective.
  2. It performs better. I iterated each solution 1,000,000 times, and the first solution performed the fastest.

Below is the table of my performance test, in case you’re interested. It shows the time in milliseconds for 1,000,000 iterations.

Solution Time
String manipulation

201

LINQ

511

TextInfo.ToTitleCase

361

 

Please let me know if you can think up other implementations for capitalizing letters.

Technorati Tags: ,,,
.Net, ASP.NET, C#

Detect when another site is unavailable. (404 detection)

A long time ago we used to store our code on punched cards.  Since that time, our development tools improved a lot.  Thanks to more powerful languages and tools, it became easier for us to write code, and as a result, our applications became more and more complex.  In 1986 Fred Brooks predicted exactly that in his article “No Silver Bullet”.  Today, any modern application uses third party libraries or components.  Our web apps need to integrate with other sites to use their services. But what do you do if the third party site is down?

At first, the problem doesn’t seem that difficult, but then I realized that it’s impossible to detect with JavaScript when another site is unavailable. (Please let me know if I’m wrong.)  If it would be possible to do this with client scripting, it would be huge security hole.  Since the release of Netscape Navigator 2.0 in 1996, browsers prevent access to most methods and properties across pages on different sites.  Today, this policy is known as Same Origin Policy.

The solution I came up with is to ping the third party host on the server side before JavaScript is loaded.  If I get a good response, then I proceed with my JavaScript; otherwise, it’s redirected to my error page.

Here’s a sample how you can check if the host available with ASP.NET:

protected void Page_Load(object sender, EventArgs e)
{
    HttpWebResponse response;
    try
    {
        var request = 
            (HttpWebRequest)WebRequest.Create("http://www.someSite.com/camdsa");
        response = request.GetResponse() as HttpWebResponse;
    }
    catch (WebException webException)
    {
        Response.Redirect("ErrorPage.aspx?status=" + webException.Status);
        return;
    }
}

If GetResponse() throws a WebException, it means that something went wrong with our request.  We can figure out what’s wrong by analyzing the WebException Status and Response properties.

kick it on DotNetKicks.com

.Net, C#, VB.NET

Keywords as variables/identifiers. Why?

I use words variable and identifier interchangeably.

Have you ever tried to use a keyword as a name of your variable?  Until recently I thought it was impossible.  However, C# and VB.NET allow developers to use keywords as variables.

string string = '' '';
Dim String As String = '' ''

If you try to compile this code, compiler will generate three errors:

  • Error    1    Identifier expected; ‘string’ is a keyword
  • Error    2    Identifier expected
  • Error    3    Invalid expression term ‘string’ 

To fix this error in C# you just prefix your variable with an @ character.  In VB.NET you surround the variable with square brackets [].  A variable or identifier with an @ prefix is called a verbatim identifier.

string @string = '' '';
Dim [String] As String = '' ''

Why anybody would use keywords as variables?  To me it looks like a very BAD practice.  Variables/identifiers must be descriptive.  Can you think of any keyword that would be descriptive enough to use in your code as a variable?

I found in C# specification why Microsoft includes verbatim identifier in their languages:

The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix.

I still believe it’s a BAD idea.

I also understand that if today I don’t see any reason to use verbatim identifiers, tomorrow I might find a perfect application for it.

If you use it and have a good reason, please let me know.

kick it on DotNetKicks.com

C#

Fun with Empty String.

I am faster.

Everyone uses pretty heavily  IsNullOrEmpty function that is a member of String class.  But sometimes we need to implement different behavior for an Empty value versus the null one.  There are multiple ways we can check for an Empty value.

Here are three different ways I come up with:

public bool IsEmpty_1(string text)
{
    return text == "";
}
public bool IsEmpty_2(string text)
{
    return text.Equals(string.Empty);
}
public bool IsEmpty_3(string text)
{
    return text.Length == 0;
}

After looking at these functions in Reflector, it was obvious that the method that uses Length should be the most efficient.  To prove it I created a little Console application that executes each comparison 100,000,000 times.  Here’s the code that does it:

equality code

Here’s the result:

equality output

The result above compares empty string “” to “text”.

"text" == ""
"text".Equals("")
"text".Length == 0

You can see that statement with equality operator (==) executes slower than the one with Equals function.  However if we compare empty string with empty string we would have different result.

"" == ""
"".Equals("")
"".Length == 0

Here’s the output when comparing empty string with empty string.

equal output

I am more readable.

Efficient code is important but I would chose the most readable code.  Unfortunately we cannot prove with numbers which code is more readable.   It can be very subjective which code is easier to read but in any case I’ll be brave enough and make my recommendations.

I would extend String class with extension method.

public static class StringUtils
{
    public static bool IsEmpty(this string text)
    {
        return text.Length == 0;
    }
}

Now we can write code like this:

"text".IsEmpty();

We can go further and create extension methods like IsNull and IsNullOrEmpty:

public static bool IsNullOrEmpty(this string text)
{
    return string.IsNullOrEmpty(text);
}

public static bool IsNull(this object obj)
{
    return obj == null;
}

You probably think why do we need to extend with  IsNullOrEmpty; it’s already part of String class.  You don’t but I think it’s more readable.  Look at two statements bellow. Which one makes more scenes to you?

string.IsNullOrEmpty(text);
text.IsNullOrEmpty();

One more note that IsNull extension method you can use with any object not just String.

List<int> numbers;
if (numbers.IsNull())
  ....

kick it on DotNetKicks.com