c# - Why should i use implicit/explicit operator? -
check code bellow:
class money { public money(decimal amount) { amount = amount; } public decimal amount { get; set; } public static implicit operator decimal(money money) { return money.amount; } public static explicit operator int(money money) { return (int)money.amount; } }
i dont understand how useful in code, couldnt method like:
public static int returnintvaluefrom(money money) { return (int)money.amount; }
would not easier , clearer implement?
this done allow money added other money. without piece of code, cause compiler error, "operator '+' cannot applied operands of type 'money' , 'int'"
money money = new money(5.35m); decimal net = money + 6;
with casting operator present allows these types of conversions made without throwing exception. can assist in readability , allow polymorphism different currencies implement own types of casts example.
Comments
Post a Comment