Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / New Users / September 2004

Tip: Looking for answers? Try searching our database.

C# Reflection: const string from enum; how to

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Stuart Baker - 15 Jul 2004 14:17 GMT
HI there:

Without delving into too much detail I wish to accomplish
the following:

Given:

enum enumError
{
  TooBig,
  TooSmall,
  Mandatory,
}

const string TooBig = "Oi - this exceeds your limit!";
const string TooSmall = "oooh! Not big enough!";
const string Mandatory = "just got to have it!";

private string GetErrorMessage(enumError err)
{
// what goes here to convert err into
// the required constant?
}

I have found some ways around using reflection but these
are not want I wanted to achieve. For example a hashTable
keyed on (int)err or inedxing into an array... I was just
hoping for a soluition using reflection. I've managed to
convert strings to enum - this one stumps me though :)

Help would be gratefully received.

Stu
Jon Skeet [C# MVP] - 15 Jul 2004 14:31 GMT
> Without delving into too much detail I wish to accomplish
> the following:
[quoted text clipped - 23 lines]
> hoping for a soluition using reflection. I've managed to
> convert strings to enum - this one stumps me though :)

Here's some sample code:

using System;
using System.Reflection;

enum EnumError
{
  TooBig,
  TooSmall,
  Mandatory,
}

class EnumErrorDescriptions
{
   const string TooBig = "Oi - this exceeds your limit!";
   const string TooSmall = "oooh! Not big enough!";
   const string Mandatory = "just got to have it!";
   
   internal static string GetErrorMessage (EnumError err)
   {
       string enumName = err.ToString();
       
       FieldInfo fi = typeof(EnumErrorDescriptions).GetField
           (enumName, BindingFlags.Static|BindingFlags.NonPublic);
       if (fi==null)
       {
           // Oops! You could throw an exception here if you wanted -
           // or return another constant, maybe.
           return "Unknown error";
       }
       return (string)fi.GetValue(null);
   }
}

class Test
{
   static void Main()
   {
       Console.WriteLine (EnumErrorDescriptions.GetErrorMessage
                          (EnumError.TooBig));
   }
}

If you'll go through this code path frequently in the same run, you
might want to put the value into a hashtable, only looking it up if you
haven't done so before.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Richard Blewett [DevelopMentor] - 12 Sep 2004 08:39 GMT
I solved this problem using a custom attribute which I applied to the enum entries:

enum enumError
{
    [ErrorDesc("Oi - this exceeds your limit!")]
    TooBig,
    [ErrorDesc("oooh! Not big enough!")]
    TooSmall,
    ...
}

I blogged about it (with the full code) here:

http://staff.develop.com/Richardb/weblog/CategoryView.aspx/.NET

Its near the bottom. I would provide a direct link but there is something not quite right about that one entry as far as my blog engine is concerned:-|

Look for "Extending the humble enum"

The thing I linked about this approach is that the descriptions are bound to the enum rather than being held in some external resource

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

?
nntp://news.microsoft.com/microsoft.public.dotnet.framework/
Stuart Baker  wrote:
> Without delving into too much detail I wish to accomplish the
> following:
[quoted text clipped - 21 lines]
> reflection. I've managed to convert strings to enum - this one stumps
> me though :)

Here's some sample code:

using System;
using System.Reflection;

enum EnumError
{
TooBig,
TooSmall,
Mandatory,
}

class EnumErrorDescriptions
{
const string TooBig = "Oi - this exceeds your limit!"; const string TooSmall = "oooh! Not big enough!"; const string Mandatory = "just got to have it!";

internal static string GetErrorMessage (EnumError err) { string enumName = err.ToString();

FieldInfo fi = typeof(EnumErrorDescriptions).GetField
(enumName, BindingFlags.Static|BindingFlags.NonPublic);
if (fi==null)
{
// Oops! You could throw an exception here if you wanted - // or return another constant, maybe.
return "Unknown error";
}
return (string)fi.GetValue(null);
}
}

class Test
{
static void Main()
{
Console.WriteLine (EnumErrorDescriptions.GetErrorMessage
(EnumError.TooBig));
}
}

If you'll go through this code path frequently in the same run, you might want to put the value into a hashtable, only looking it up if you haven't done so before.

--
Jon Skeet -
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

[microsoft.public.dotnet.framework]

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.