Posted by: Zeeshan Amjad | December 16, 2011

One more Visual Studio designer tip


We saw one small Visual Studio designer tip here. Now we are going to see one more tip. We studied few example of Value converter. Lets take a look at one example of IMultiValueConverter we discuss here. Here is our code.

Code Snippet
#region IMultiValueConverter

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    string firstName = values[0] as string;
    string lastName = values[1] as string;

    return string.Format("{0}, {1}", lastName, firstName);
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    throw new NotImplementedException();
}

#endregion

 

Here we are using as operator to check and cast the value into string type. We can directly cast it into string too, because we already know that the value is string. Here is our alternate code.

Code Snippet
#region IMultiValueConverter

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    string firstName = (string)values[0];
    string lastName = (string)values[1];

    return string.Format("{0}, {1}", lastName, firstName);
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    throw new NotImplementedException();
}

#endregion

 

And program works exactly the same. Now take a look at the designer. We will get this error at design time.

DesignerError

The reason is that as operator is not throwing an exception if not able to cast into target type. It simply returns null. Therefore it is better to use the as operator and check for null after that while implementing value converter to get an expected design time result.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: