0

I am using below code to convert a string value to integer and set in nullable integer variable only if value is greater then zeor '0'.

NOTE: its working fine but i want experts advice to optimize it and make it a library function.

if (txtdownload.Text.Trim() != "") { int i = 0; int.TryParse(txtdownload.Text, out i); if (i > 0) { pad.Noofdownload = i;//Noofdownload is a property on nullable integer } } 

Please help to create a Optimized library function (common function), which i can use for all such a conversion.

Thanks a lot.

NOTE: i have created below library function but its not working for properties as we can't pass properties as a ref.

 public static void getValueFromTextBoxInNullable(string srctext,ref int? dest) { if (srctext.Trim() != "") { int j = 0; int.TryParse(srctext , out j); if (j > 0) { dest = j; } } } 
1
  • This should be migrated to codereview.stackexchange.com as there is no problem, just a desire for a better version. (I realised this after I answered it) Commented Jun 14, 2011 at 6:11

1 Answer 1

3

This is an extension method that should do the job:

public static int? ToNullableInt(this string source) { var i = 0; return int.TryParse(source, out i) ? (int?)i : null; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.