In search of default properties |
Written by Mike James | ||||||
Wednesday, 13 April 2011 | ||||||
Page 2 of 2
Operator overloadingOne way of creating a default property would be to overload the assignment operator for the type in question. This is a good idea but unlike C++ you can't overload the assignment operator in C#. You can override the + operator however and this can be used in combination to give += say. However as we will discover this isn't particularly useful. For example to override the + operator you might use something like: static public int operator +(int d, stack s) Following this you can write MyStack.push(40); and the result will be 40+10. However if you want to do 10+MyStack you also need: static public int operator +(int d, stack s) These two custom operators allow you to use a stack in an arithmetic expression like: MyStack.push(50); You can also define custom operators for the other basic operators -, * and / just as easily and then you really can write arbitrary expressions involving a stack. The one thing you cannot do is write MyStack=10; or int value=MyStack; because the assignment operator hasn't been overloaded. However you can write: int value = 1; because the += is decomposed into value=value+MyStack; and the + sign is overloaded correctly. Implicit conversionThere are various ricks you can use to implement a default property that doesn't rely on the use of indexers or operator overloading but they only work in limited ways. You can however make the assignment int value=MyStack; work very easily. All you have to do is define an implicit conversion operator which converts the MyStack object into a suitable int by accessing the "default" property. For example: public static implicit operator int(stack ms) Now you can write: MyStack.push(80); However you still can't write MyStack=90; and there is no way that you can easily write an implicit conversion operator that converts an int to a stack. The reason is that you have no knowledge of the left hand side of the assignment in an implicit conversion operator - you only know about the right hand side i.e. the int in this case. Your only real choice is to generate a new stack object, store the int in it using push and return that to be assigned to MyStack. Of course this has the effect of resetting the state of the stack which is not what was required. Is there a clever way of achieving the result using say introspection or the dynamic language run time? If you have any solutions email me: Until then these solutions are as close as we can get to default properties in C#.[
You can download the code from the CodeBin (note you have to register first). If you would like to be informed about new articles on I Programmer you can either follow us on Twitter or Facebook or you can subscribe to our weekly newsletter.
<ASIN:1449380344> <ASIN:0123745144> <ASIN:0321658701> <ASIN:0321741765> |
||||||
Last Updated ( Monday, 12 July 2021 ) |