Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend THE class, not the instance? [duplicate]

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)?

like image 491
BeemerGuy Avatar asked Jul 01 '26 11:07

BeemerGuy


2 Answers

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.

like image 74
Joachim VR Avatar answered Jul 03 '26 01:07

Joachim VR


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.

like image 38
KeithS Avatar answered Jul 03 '26 00:07

KeithS