473,597 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Alternative to Enum string values as return types and parameters

I know that string/char enum is not possible in c# (.NET2.0)
I need to create the equivalent of this:

public enum HOW_GOOD
{
AWESOME = "A",
GREAT= "G",
NOT_TOO_BAD = "N",
TERRIBLE="T"
}

i wanted to use this enum as a parameter/ return type for methods

Eg
public HOW_GOOD HowAreYouFeelin g(string MyName)

{
return HOW_GOOD.NOT_TO O_BAD;
}
or

public string HowAreYouFeelin g(HOW_GOOD m_HowGood)

{

return "Not Too Bad";
}
The rationale behind this is that this approach makes better readability for
the developers and makes my DBA happy :) as I will store only char values in
the DB. The dataset table results will have the char value too. However, if
I am forced to use enum's then the only alternative is numbers which are
really meaningless by themselves.

Thanks in advance

Sanjay
Nov 17 '05 #1
3 13894
Sanjay,

What I would do is use an enumeration with numbers. Then, to each field
of the enumeration, I would attach an attribute with the information that is
related to that enumeration member. For example, you could create an
attribute named HowGoodAttribut e which takes a string in the constructor,
and has one property, the string that is passed in the constructor. Then,
you would do something like this on your enumeration:

// HOW_GOOD doesn't follow the public naming conventions for .NET, btw
public enum HowGood
{
[HowGood("A")]
Awesome,
[HowGood("G")]
Great,
[HowGood("N")]
NotTooBad,
[HowGood("T")]
Terrible
}

Then, when you need to access the string, you can use reflection to get
the attribute using the enumeration value. Basically, what you do is take
the string name of the enumeration value and get the static field that is
attached to that enumeration's type. Once you have the FieldInfo for that
field, you can get the attribute through a call to GetCustomAttrib utes.
With the attribute in hand, you can get the string assigned to it easily.

This way, you can pass around the enumeration value, and when you need
the extra information, get it from the attribute.

I've done this so many times that I wrote some utility methods that
handle that (it takes a type, the enumeration value, and optionally, the
type of attribute to get). It's a great use of attributes, IMO, and also a
good way to store more complex static data.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Sanjay Pais" <sa****@nospam. com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I know that string/char enum is not possible in c# (.NET2.0)
I need to create the equivalent of this:

public enum HOW_GOOD
{
AWESOME = "A",
GREAT= "G",
NOT_TOO_BAD = "N",
TERRIBLE="T"
}

i wanted to use this enum as a parameter/ return type for methods

Eg
public HOW_GOOD HowAreYouFeelin g(string MyName)

{
return HOW_GOOD.NOT_TO O_BAD;
}
or

public string HowAreYouFeelin g(HOW_GOOD m_HowGood)

{

return "Not Too Bad";
}
The rationale behind this is that this approach makes better readability
for the developers and makes my DBA happy :) as I will store only char
values in the DB. The dataset table results will have the char value too.
However, if I am forced to use enum's then the only alternative is numbers
which are really meaningless by themselves.

Thanks in advance

Sanjay

Nov 17 '05 #2
One way, would be to use the [Description()] attribute (found within
System.Componen tModel before each tag, so your enum would end as:

public enum HOW_GOOD
{
[Description("Aw esome")]
AWESOME = "A",
[Description("Gr eat")]
GREAT= "G",
[Description("No t Too Bad")]
NOT_TOO_BAD = "N",
[Description("Te rrible")]
TERRIBLE="T"
}

And every time you want the description, use the following function:

public static string GetEnumDescript ion(object value)
{
string retVal = "";
try
{
FieldInfo fieldInfo = value.GetType() .GetField(value .ToString());
DescriptionAttr ibute[] attributes =
(DescriptionAtt ribute[])fieldInfo.GetC ustomAttributes
(typeof(Descrip tionAttribute), false);
retVal =
((attributes.Le ngth>0)?attribu tes[0].Description:va lue.ToString()) ;
}
catch( NullReferenceEx ception )
{
//Occurs when we attempt to get description of an enum value that
does not exist
retVal = "Unknown";
}
return retVal;
}

One warning about this though... because this uses reflection to get the
string, it does cost you a bit of time, so if this is being done a lot back
to back, you might want to think about caching.

Brendan
"Sanjay Pais" wrote:
I know that string/char enum is not possible in c# (.NET2.0)
I need to create the equivalent of this:

public enum HOW_GOOD
{
AWESOME = "A",
GREAT= "G",
NOT_TOO_BAD = "N",
TERRIBLE="T"
}

i wanted to use this enum as a parameter/ return type for methods

Eg
public HOW_GOOD HowAreYouFeelin g(string MyName)

{
return HOW_GOOD.NOT_TO O_BAD;
}
or

public string HowAreYouFeelin g(HOW_GOOD m_HowGood)

{

return "Not Too Bad";
}
The rationale behind this is that this approach makes better readability for
the developers and makes my DBA happy :) as I will store only char values in
the DB. The dataset table results will have the char value too. However, if
I am forced to use enum's then the only alternative is numbers which are
really meaningless by themselves.

Thanks in advance

Sanjay

Nov 17 '05 #3
A simple solution would be
public class HowGood
{
public const string Awesome = "A";
public const string Great = "G";
public const string NotTooBad = "N";
public const string Terrible = "T";
}

You could then use the class variables just as an enum: HowGood.Awesome ,
HowGood.Great ...

I changed the capitalization to keep in line with casing-conventions but you
can use what you want...

Cois

"Sanjay Pais" <sa****@nospam. com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I know that string/char enum is not possible in c# (.NET2.0)
I need to create the equivalent of this:

public enum HOW_GOOD
{
AWESOME = "A",
GREAT= "G",
NOT_TOO_BAD = "N",
TERRIBLE="T"
}

i wanted to use this enum as a parameter/ return type for methods

Eg
public HOW_GOOD HowAreYouFeelin g(string MyName)

{
return HOW_GOOD.NOT_TO O_BAD;
}
or

public string HowAreYouFeelin g(HOW_GOOD m_HowGood)

{

return "Not Too Bad";
}
The rationale behind this is that this approach makes better readability
for the developers and makes my DBA happy :) as I will store only char
values in the DB. The dataset table results will have the char value too.
However, if I am forced to use enum's then the only alternative is numbers
which are really meaningless by themselves.

Thanks in advance

Sanjay

Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3726
by: Fao | last post by:
Hi, I am in my first year of C++ in college and my professor wants me to Write a Program with multiple functions,to input two sets of user-defined data types: One type named 'Sign' declared by "typedef" to contain only either +10 or -10 and the other type named Color declared by "enum" to contain only black, blue, purple, red, white, and yellow.
4
6479
by: Nikhil Patel | last post by:
Hi all, I am a VB6 programmer and learning C#. I am currently reading a chapter on types. I have question regarding enums. Why do we need to convert enum members to the value that they represent? Thanks in advance... -Nikhil
43
6859
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's another story.) The data is written once and then read many times. Each primitive read requires unboxing. The data reads are critical to overall app performance. In the hopes of improving performance, we have tried to find a way to avoid the...
21
4581
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
10
7117
by: Ken Allen | last post by:
The ToString() function, when applied to a variable that is an enumeration type, results in a string that is the name of the enumerated value that was defined in the source code. This is cool, but how does one override the function to have some values return a different string? For example, suppose I have an enum with value for the types of DVD media like public enum DVD_Media {
4
1478
by: UJ | last post by:
I know how to define enums, and they work great. But is there any way to define the same time of thing but give them actual values? For instance, I'd like to define something with the idea like this: Public Enum TMCContentStatus as string PrevApproved = "P" ToBeAdded = "A"
13
12371
by: Don | last post by:
How do I get an Enum's type using only the Enum name? e.g. Dim enumType as System.Type Dim enumName as String = "MyEnum" enumType = ???(enumName)
34
11161
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code snippet that I wrote today that gives me an instant implementation of the pattern. I could easily just always use such an implementation instead of a standard enum, so I wanted to know what you experts all thought. Is there a case for standard enums?
3
3035
by: hufaunder | last post by:
Imagine you have a charting library that can draw lines, bars, floating bars, bands, etc. Lines and bars need only one input. Floating bars and bands need two inputs. There are two approaches: 1) One enum with all 4 types (bars, band, etc). One chart class that accepts up to 2 arrays of values. If the user choses a band but there is only one input array throw an exception. If the user passes two input arrays with different lengths throw...
0
7884
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8380
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6681
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5844
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5423
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3880
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2394
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1229
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.