c# - how to create a custom cast explicit in c #? -
have code:
string abc = "123456"; to convert int should use convert:
int abcint = convert.toint32(abc); the problem if not number have exception see returning 0 final code like:
try{ int abcint = convert.toint32(abc); }catch(exception e){ int abcint = 0; } so see decided create book made me object returning 0 numeric without exception if failed, keep flexible programming without junk code:
int abcint = libs.str.safeint(abc); the code is:
public int safeint(object ob) { if ((ob == null) || (string.isnullorempty(ob.tostring()))) return 0; try { return convert.toint32( system.text.regularexpressions.regex.replace(ob.tostring(), @"@[^ee0-9\.\,]+@i", ""). tostring(cultureinfo.invariantculture.numberformat) ); } catch (formatexception e) { return 0; } } but want go 1 step further , this:
int abcint = (safeint)abc; how do?
can not convert type 'string' 'libs.safeint.safeint'
you should use int32.tryparse:
int abcint; if(!int32.tryparse(abc, out abcint)) { abcint = 0; } // abcint has been parsed int, or defaulted 0 note can shortened to
int abcint; int32.tryparse(abc, out abcint); if want default value 0 because:
when method returns, contains 32-bit signed integer value equivalent number contained in
s, if conversion succeeded, or zero if conversion failed. conversion fails ifsparameternull, not of correct format, or represents number lessminvalueor greatermaxvalue. parameter passed uninitialized.
i recommend against writing way because can't distinguish between abc = "0" , abc = "garbage"; both exhibit same behavior above 2 lines of code. initial version above (i.e., if, can distinguish 2 cases if need to; silently ignoring errors generally bad idea).
that said, if absolutely dying know how implement explicit cast operator, proceed this:
class safeint32 { private readonly int value; public int value { { return this.value; } } private readonly string source; public string source { { return this.source; } } private readonly bool successful; public bool successful { { return this.successful; } } public safeint32(string source) { this.source = source; this.successful = int32.tryparse(source, out this.value); } public static explicit operator safeint32(string source) { return new safeint32(source); } public static implicit operator int(safeint32 safeint32) { return safeint32.value; } } usage:
int abcint = (safeint32)"123456"; note had define explicit cast operator cast string safeint32, , implicit cast operator cast safeint32 int achieve desired syntax. latter necessary compiler can silently convert result of (safeint32)"123456" int.
again, recommend against this; use int32.tryparse.
Comments
Post a Comment