generics - Casting Between Data Types in C# -
i have (for example) object of type want able cast type b (similar how can cast int
float
)
data types , b own.
is possible define rules casting occurs?
example
int = 1; float b = (float)a; int c = (int)b;
yes, possible using c# operator overloading. there 2 versions explicit , implicit.
here full example:
class program { static void main(string[] args) { a1 = new a(1); b b1 = a1; b b2 = new b(1.1); a2 = (a)b2; } } class { public int foo; public a(int foo) { this.foo = foo; } public static implicit operator b(a a) { return new b(a.foo); } } class b { public double bar; public b(double bar) { this.bar = bar; } public static explicit operator a(b b) { return new a((int)b.bar); } }
type can cast implicitly type b type b must cast explicitly type a.
Comments
Post a Comment