In the early days of .NET, I believe there was an attribute you could decorate a class with to specify a default property.
According to some articles I've found, this appears to have been yanked from the framework at some point, because it was a little confusing, and I can see how that is the case.
Still, is there another way to get the functionality it provided?
It looked something like this:
<DefaultProperty("Value")> _
Public Class GenericStat
...
Public Property Value() As Integer
...
End Property
...
End Class
This allowed you to do Response.Write(MyObject)
instead of Response.Write(MyObject.Value)
... This is not a terribly clunky example, but in some complex object-oriented contexts it gets a little hideous. Please let me know if there is a better way.
Note: I am not looking for the Default keyword, which can only be used on properties that take a parameter.
I've been looking for an answer to a similar problem and in the process I stumbled across this here. Actually John's answer pointed me into the direction I needed to go. And it might help with the original question as well:
My Problem: I needed something that I could use just like an Integer
...and so on... However I needed additional things as well
(actually those readonly Properties could be Methods as well ...)
etc... So I really needed an Object
I was thinking of extension methods for Integer ( @ _ @ ) ... I didn't want to go down that road ...
I also thought of writing a "ReadOnlyPropertyOracle" as a separate class and give it Methods like
weeeell .... That would have worked but looked gruesome ...
So in came John's Hack and Brian MacKay's comment about operators: Combining both, widening/narrowing conversion operators (for assignment) and comparison operators for ... well comparision. Here is part of my code and it does what I need:
Yes, this will still be 1-2 dozen one-line operator definitions but most of them are trivial with little room for error ;-) So this works for me...
Hi John your answer was very useful! I changed for use with any type, thanks.
And the usage:
I've found that you can do exactly what the original poster wanted using
Widening Operator CType
This was mentioned above but without much detail, so I entirely missed it as I was trying to find an answer to this question. This methodology doesn't define a default property, per se, but it achieves the same result.So now
and
both work without the
.Value
reference and without an indexer such asmyobject(1)
You could override the ToString method to output Value as a string so that when you do Response.Write(MyObject), you get the same effect.
[EDIT] Now that I understand it better, why not just provide a way to get directly at the values of the contained objects.