C# "as" keyword with objects of various types
How to correctly rewrite this code to be foolproof versus various types of input parameter? C开发者_高级运维urrently this code fails if, for instance, input parameter is a valid instance of DateTime
. I've just figured that out - it was wrongly returning false
for todays date.
public override bool IsValid(object value)
{
string field = value as string;
if (String.IsNullOrEmpty(field))
return false;
return true;
}
Would be nice to know if this is possible without having multiple if statements (for every possible value type and even for some reference types, like the string).
EDIT: oh, of course, the requirement is for the object to not be null or whitespace (therefore it has to be castable or parsable to string, I guess).
Your use of as
seems atypical and unnecessarily obscure. Given that you goal is to return false if the object is null or empty, use this code instead:
public override bool IsValid(object value)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return false;
return true;
}
If you are using .NET 4 and want to check for whitespace also and not just empty strings, the new string.IsNullOrWhiteSpace()
would be worth looking at instead of string.IsNullOrEmpty()
.
why not using value.ToString()
? [After null check]
public override bool IsValid(object value)
{
if(value==null)
return false;
string field = value.Tostring();
if (String.IsNullOrEmpty(field))
return false;
return true;
}
Any object can be converted to string, as it has a ToString method. Check if the reference is null, then turn it into a string and check the length:
public override bool IsValid(object value) {
return value != null && value.ToString().Length > 0;
}
精彩评论