Vadim's Weblog

Never stop learning.

Archive for the ‘C#’ Category

Capitalize only first character. (C#)

Posted by Vadim on October 9, 2013

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







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

Technorati Tags: ,,,

Posted in C# | Tagged: , , , | 3 Comments »

Detect when another site is unavailable. (404 detection)

Posted by Vadim on December 25, 2010

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;
        var request = 
        response = request.GetResponse() as HttpWebResponse;
    catch (WebException webException)
        Response.Redirect("ErrorPage.aspx?status=" + webException.Status);

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

Posted in .Net, ASP.NET, C# | Tagged: | 1 Comment »

Keywords as variables/identifiers. Why?

Posted by Vadim on May 13, 2009

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

Posted in .Net, C#, VB.NET | 9 Comments »

Fun with Empty String.

Posted by Vadim on February 23, 2009

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".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.

"" == ""
"".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:


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?


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

Posted in C# | 10 Comments »

WPF Margin demystified.

Posted by Vadim on October 13, 2008

In my previous post I asked a question about this line of code:

<Button Margin="10 5" />


In XAML we can assign margin to a control three different ways:

<Button Margin="5" />
<Button Margin="10 5" />
<Button Margin="10 5 10 10" />
  • The first line assigns left, top, right, and bottom margins with value 5.
  • The second line assigns left and right margins with value 10 but top and bottom with value 5.
  • The last line assigns left, right, and bottom with value 10 and top would have value 5.

If we try to do the same in the code behind, it would look like this:

button.Margin = new Thickness(5);
button.Margin = new Thickness(10, 5, 10, 10);

You can see in the code above that we have code for line 1 & 3 only.  I couldn’t find the way to create code behind for second line because there’s no Thickness constructor with two parameters.

Thanks to Rune Jacobsen & Sam who provided some clues in comments to my previous article.


After I read Sam’s comment:

The converter at work here is a ThicknessConverter which parses the input string and attempts to map the values given in the string to one of the Thickness object constructor overloads.

, I used .NET Reflector to analyze ThicknesseConverter class.

ThicknesseConveter has a public method ConvertFrom that calls internal method FromString.

public override object ConvertFrom(
    ITypeDescriptorContext typeDescriptorContext,
    CultureInfo cultureInfo,
    object source)
     . . .
    if (source is string)
        return FromString((string) source, cultureInfo);
     . . .

FromString method is responsible for parsing string values like “10, 5, 10, 10” and converting them into Thickness.

It means that this code

<Button Margin="10 5" />

will be converted by FromString method into:

new Thickness(numArray[0], numArray[1], numArray[0], numArray[1]);

Bellow is a switch statement in FromString method that explains the magic.

internal static Thickness FromString(string s, CultureInfo cultureInfo)
     . . .
    switch (index)
        case 1:
            return new Thickness(numArray[0]);
        case 2:
            return new Thickness(numArray[0], numArray[1], numArray[0], numArray[1]);
        case 4:
            return new Thickness(numArray[0], numArray[1], numArray[2], numArray[3]);
     . . .

If you want to assign a margin with two doubles from the code behind, you can do it like this:

button.Margin =
    (Thickness)new ThicknessConverter()
        .ConvertFrom(null, CultureInfo.CurrentCulture, "5, 10");

Mystery is solved.

kick it on

Posted in .Net, C#, WPF, XAML | 2 Comments »

WPF Margin Property

Posted by Vadim on October 5, 2008

I finally decided to spend some time to learn WPF.  One of the thing I learned today is Margin property.

<Button Margin="10 0 10 5" />

Every control that derives from FrameworkElement class has this WPF_Margin property.

I’m not going to describe this property here. However, I want to share with you how I memorized the sequence of margin.  It goes like this: Left, Top, Right, Bottom.

The easiest way for me to remember is to start from Left and then go clock wise: Top, Right, Bottom.

There are two main reasons why I blog and both of them selfish.

First reason is because writing helps me remember and understand better new things I learn.

The second reason is that people who read my blog comment and correct any mistakes I make and that helps me to learn too.

I have a question for WPF gurus.  I understand that if all margins are the same (for example left, top, right, and bottom are equal to 5), it’s possible to assign margin like this:

<Button Margin="5" />

The both assignments with one number and four numbers make sense because Margin is of type Thickness  and this struct has two constructors:

public Thickness(double uniformLength)
public Thickness(double left, double top, double right, double bottom)

Here comes my question: I discovered that it’s possible to assign Margin declaratively with two numbers.

<Button Margin="10 5" />

How is it possible if Thickness doesn’t have a constructor with two parameters?
kick it on

Posted in .Net, C#, WPF | 15 Comments »

How big is null in Nullable types?

Posted by Vadim on July 28, 2008

I use often Nullable types in my code.  However, when today I was debugging my code I was surprised to learn that the expression bellow equals to false:

   1: int? n1 = null;
   2: int? n2 = null;
   3: if (n1 <= n2)
   4:     Console.WriteLine("not going to happen");

I decided to dig deeper to see what the reason for this behavior.

I learned that when you have a Nullable type variable that is null (int? n1 = null) in relation comparison expression, the expression is always false.  By relation comparison I mean binary comparison with one of following operators: <, >, <= , =>.

Let me try to explain why this happens.   Let assume that we have two Nullable integers n1 and n2.  n1 is null and n2 has value of 5.  When you compare (n1 < n2), behind the scene the following comparison happens:

    (n1.GetValueOrDefault() < n2.GetValueOrDefault()) && 
    (n1.HasValue & n2.HasValue)

n1.GetValueOrDefault() will return 0.

n2.GetValueOrDefault() will return 5.

That means the first part of our expression will be true because 0 is less than 5.  However the second part of our expression will be translated into (false & true) which equals to false.  So the first expression is true and the second one is false that means that the whole expression is false too.

That explains why any relation comparison with null value will be false.

kick it on

Posted in .Net, C#, Coding, Nullable Types | 1 Comment »

Explaining GetHashCode method.

Posted by Vadim on July 5, 2008

Every object you ever created or used in .NET has GetHashCode method along with Equals, GetType, and ToString methods.  This method is an instance method of an Object class from which any other class derives.


GetHashCode() method returns an integer that identifies an object instance.  I also can repeat MSDN documentation but you can read it on your own.

You would want to override this method along with Equals() method in your class if the object of your class is going to be used as a key in Hashtable.

The best way to explain it is to show an example. In I was using class Point as an example.  I’m going to continue with this class.  So let assume that we have class like this:

   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11: }

Next we want to use Point as a key in a Hashtable.  Remember that the key of the Hasthable must be unique.  In the code bellow we have two identical keys (line 2 & 4). We should expect ArgumentException.

   1: Hashtable hashtable = new Hashtable();
   2: hashtable.Add(new Point(2, 3), "Point 1");
   3: hashtable.Add(new Point(5, 3), "Point 2");
   4: hashtable.Add(new Point(2, 3), "Point 3");

However, no exception was thrown.  There are two reasons why exception is not thrown:

  1. Equals() method that is also an instance method of Object class will always indicate that Point in line 2 and line 4 are different. This expected because two objects have different references.
  2. GetHashCode() method returns different number for these objects.

Try to execute code bellow:

   1: static void Main(string[] args)
   2:  {
   3:    var point1 = new Point(2, 3);
   4:    var point2 = new Point(2, 3);
   5:    Console.WriteLine("point1 Hash: {0}"
   6:         , point1.GetHashCode());
   7:    Console.WriteLine("point2 Hash: {0}"
   8:         , point2.GetHashCode());
   9:    Console.WriteLine("point1 equal to point2: {0}"
  10:         , point1.Equals(point2));
  11:  }

You will get output similar to this one:

point1 Hash: 58225482
point2 Hash: 54267293
point1 equal to point2: False

You can see that we got different hash codes.

To solve this problem we override Equal() and GetHashCode() in our Point class.

First we override Equals() method:

   1: public override bool Equals(object obj)
   2: {
   3:   if (ReferenceEquals(null, obj)) return false;
   4:   if (ReferenceEquals(this, obj)) return true;
   5:   return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
   6: }

You can see that I use ReferenceEquals() method that is static method of Object class.  It checks if the specified objects are the same.

Next we override GetHashCode() method:

   1: public override int GetHashCode()
   2: {
   3:   unchecked
   4:   {
   5:     return (_x * 397) ^ _y;
   6:   }
   7: }

The whole Point would look like this:

   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  12:   public override bool Equals(object obj)
  13:   {
  14:     if (ReferenceEquals(null, obj)) return false;
  15:     if (ReferenceEquals(this, obj)) return true;
  16:     return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
  17:   }
  19:   public override int GetHashCode()
  20:   {
  21:     unchecked
  22:     {
  23:       return (_x * 397) ^ _y;
  24:     }
  25:   }
  26: }

Now if you try to execute the application the output should look exactly like this:

point1 Hash: 793
point2 Hash: 793
point1 equal to point2: True

Also if we try to add new Point(2, 3) twice, we get an ArgumentException as expected.

kick it on

Posted in .Net, C#, Coding, GetHashTable, VS2005, VS2008 | 15 Comments »

Comparing Reference Types in Unit Tests.

Posted by Vadim on July 3, 2008

If you’ve done some unit testing, you’re familiar with Assert.AreEqual method.  Have you try to compare two objects that have the same value(s) but the AreEqual method tells you that they are not equal?  For example let assume that we have a class Point:

   1: private class Point
   2: {
   3:   private int _x;
   4:   private int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11: }

And we test for the constructor:

   1: [Test]
   2: public void Point_constructor_test()
   3: {
   4:   Point point = new Point(2, 3);
   5:   Assert.AreEqual(point, new Point(2, 3));
   6: }

When I run this test using MbUnit, the assertion fails.  The reason it fails because Point is a reference type.     Actually what is getting compared is objects references (not objects values) and of course they have different references.

One way we could fix it is to make Point a Value Type by replacing class with struct.

   1: private struct Point
   2: {
   3:   private int _x;
   4:   private int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11: }

This definitely resolves the issue.

Another thing we could do is implement IEquatable<T> interface:

   1: private class Point : IEquatable<Point>
   2: {
   3:   private int _x;
   4:   private int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  12:   public bool Equals(Point other)
  13:   {
  14:     return (_x == other._x) && (_y == other._y);
  15:   }
  16: }

[Updated] However, MbUnit test still will fail because deep inside MbUnit’s AreEqual calls object.Equal(object).  In order for AreEqual to succeed in this case, it needs to call generic version of AreEqual.  Something like this:

   1: private static bool AreEqual<T>(T expected, T actual)
   2: {
   3:   if (expected is IEquatable<T> )
   4:     return ((IEquatable<T>)expected).Equals(actual);
   5:   return expected.Equals(actual);
   6: }

It means we need to modify our test little bit. Instead of AreEquals method we can use IsTrue one.

   1: [Test]
   2: public void Point_constructor_test()
   3: {
   4:   Point point = new Point(2, 3);
   5:   Assert.IsTrue(point.Equals(new Point(2, 3)));
   6: }

In software development the same problem can be solved many different ways.  I assume that most common solution is going to be comparing some public properties in the object instead of the whole object.

Let assume assume that our Point class has public properties X and Y.  Here’s an example how my test would look:

   1: [Test]
   2: public void Point_constructor_test()
   3: {
   4:   Point point1 = new Point(2, 3);
   5:   Point point2 = new Point(2, 3);
   6:   Assert.AreEqual(point1.X, point2.X);
   7:   Assert.AreEqual(point1.Y, point2.Y);
   8: }

kick it on

Posted in .Net, C#, MbUnit, Reference Type, TDD | 3 Comments »

Reference Type interview questions.

Posted by Vadim on June 30, 2008

Part of my job is to interview developers for open position at my company.  I’m surprised how many times people give wrong answers to questions related to Reference type vs. Value type.  Bellow list of the questions some interviewers get incorrectly:

Question 1: Describe behavior of the code bellow:

   1: static void Main(string[] args)
   2: {
   3:   StringBuilder builder = null;
   4:   Foo(builder);
   5:   Console.WriteLine(builder.ToString());
   6: }
   8: private static void Foo(StringBuilder builder)
   9: {
  10:   builder = new StringBuilder("Interview");
  11: }

Incorrect Answer 1: It will output “Interview”.

Correct Answer 1: NullReferenceException will be thrown on line 6.  Because builder is null and cannot access ToString() method.

Question 2: What will the output of the code bellow?

   1: static void Main(string[] args)
   2: {
   3:   StringBuilder builder = null;
   4:   Console.WriteLine(Foo(builder));
   5: }
   7: private static bool Foo(StringBuilder builder)
   8: {
   9:   return builder is StringBuilder;
  10: }

Incorrect Answer 2: True

Correct Answer 2: False

Often people are very eager to demonstrate their knowledge of the subject and they volunteer statements like this one:

Reference Types live on the heap and Value Types on the stack.

And this triggers a question like this one from me:

   1: class A
   2: {
   3:   B b = new B();
   5:   class B
   6:   {
   7:     public int i;
   8:   }
   9: }

Does it mean that in the code above b of type B will be stored on the heap but b‘s member i of type int is going to be stored on the stack?

This questions really confuses some people.

Correct statement is:

Reference Types and instance Value Types live on the heap and local Value Types live on the stack.

The purpose of this post is not to make fun but to educate.

kick it on

Posted in .Net, C#, Reference Type | 3 Comments »