How to factorise this code

M

MattC

Hi,

How can I factorise the following code to make it such that I can place it
in a base class instead of a version in each derived class:

System.Type enumtype = typeof(SortFieldEnum);
SortFieldEnum sortCol = (SortFieldEnum)SortFieldEnum.Parse(enumtype,
sortexpression);

Was trying to do the following:

public object DetermineEnum(System.Type enumtype, string sortexpression)
{
return (enumtype)enumtype.Parse(enumtype, sortexpression);
}

but having diffculty.

TIA

MattC
 
J

Jon Skeet [C# MVP]

MattC said:
How can I factorise the following code to make it such that I can place it
in a base class instead of a version in each derived class:

System.Type enumtype = typeof(SortFieldEnum);
SortFieldEnum sortCol = (SortFieldEnum)SortFieldEnum.Parse(enumtype,
sortexpression);

Was trying to do the following:

public object DetermineEnum(System.Type enumtype, string sortexpression)
{
return (enumtype)enumtype.Parse(enumtype, sortexpression);
}

but having diffculty.

Given that you've declared the method to return object, you don't need
the cast which is causing you problems - just make it:

public object DetermineEnum (Type enumType, string sortExpression)
{
return Enum.Parse (enumType, sortExpression);
}

Now, I'm not sure it's a particularly useful method, as DetermineEnum
is longer than Enum.Parse in the first place...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top