Possible Duplicate:
Can you make an Extension Method Static/Shared?
Extension methods are great! Pardon my ignorance, but so far I've only found that you can extend a class to allow methods on its instances, but not the class itself.
Here's what I'm trying to do.
I have an enum like so:
enum ViewType
{
Front_View,
Back_View
}
And I already created an extension method ToDescription() to display a user-friendly textual representation of the view type, like so:
ViewType thisview = ViewType.Front_View;
string thisviewtext = thisview.ToDescription(); // translates to "Front View"
But later in the code, I want to parse from that translation back to the type, like this potential code if assuming I can extend the enum type itself:
// !!!NOT REAL CODE YET!!!
// translate to value ViewType.FrontView
ViewType newview = ViewType.ParseFromDescription("Front View");
How do I implement that ParseFromDescription(string) extension method (if possible)?
You can't do that. You could define a static helper class ViewTypeTools containing the method. Extension methods are basically the same thing, but a bit nicer to write.
You cannot make a static method callable as if it were contained in another static class. You cannot, for instance, create a String.IsNullOrBlank() function that checks the passed string for only whitespace in addition to being null or zero-length. You would have to have access to the String class code and add the method there.
To get the result you want, I would start with the string and implement an extension method ParseDescriptionToViewType() that will take the string as its "this" parameter and output the ViewType.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With