When ever I need to convert any object value into string, I normally uses the .net function ToString(). Even though this gives me the string value but this is quite annoying sometimes because when the object value is null then it throws an Object Reference not set to an instance of object error. So to avoid this error, I have to write a check like this before using the toString function.
if(objValue != null)
{
objValue.ToString();
}
But this brings an additional task of writing this check every time in the code, which in turns makes the function body lengthy. With the implementation of .Net 3.0 Extension functionality, I could make my function clean, less lengthy and readable. More information on Extension functions can be found here.
Below is how to do this,
Firstly I added an extension function to the object type and named it as "ToValueString()"
The extension class and function definition is as follows,
{
public static string ToValueString(this object value)
{
return value == null ? string.Empty : value.ToString();
}
}
Once the above class is there in the project, then once we type the dot after the object name, then the .net intellisense will be show up and we can find the custom extension function in the list. By this way, code block can be clean, and doesn't need to bother about the Object Reference not set to an instance of object because the null check is handled inside the extension function. Since we have added the extension to object class which is the base of other .net classes this extension function will be attached to other .net class objects as well.
Another usefulness of the extension came during the validation for empty string. .Net string class comes with a useful function to check whether the string value is Null or empty, string.IsNullOrEmpty(stringValue), this work when the stringvalue is null or empty string, but to use this function effectively then we have to use trim() function to remove the unwanted empty spaces in string, but to use trim() function we again have to add a check because stringValue.Trim() will again throw Object Reference not set to an instance of object when stringValue is null.
if(stringValue != null)
{
stringValue = stringValue.Trim();
}
if(string.IsNullOrEmpty(stringValue))
{
MessageBox.Show("Value not entered");
}
So this will in turn make my function lengthy which I don't like because it just consumes developer's time and redundant code for doing the same functionality for multiple objects. The extension function again came to ease my development, I wrote one extension function for string object which can be found below,
public static bool IsNullOrEmpty(this string obj)
{
if (obj == null)
{
return true;
}
if (obj.Trim() == string.Empty)
{
return true;
}
return false;
}
In short, the extension functions are very helpful in coding and increases developer’s productivity.
No comments:
Post a Comment