what are the best practices for type conversions in C# ?
int temp=System.ConvertToInt32(Request.QueryString["Id"]);
if (temp!=null)
{ // logic goes here }
This fails if Id somehow turns out to be ‘abc’
Please advice the use of of ternary operators and other single line statements apart from if else statements (like using single line ternary operators). Also, do you guys prefer TryParse over Convert & why so ? Have your say fellows.
TryParsehas the obvious advantage that in the case of failure it will return false instead of throwing an exception.The standard pattern would be something like:
Now, it’s also worth bearing in mind that you can give
int.TryParseanIFormatProviderand aNumberStyles– for example, you may well want to specifyCultureInfo.InvariantCultureas theIFormatProviderif this is really meant to be an auto-generated ID (rather than one entered by a user).If you want to effectively have “default values” you could write a helper method like this:
You can then use this like so:
Or you could just write a method which takes a default value, of course 🙂