Hi Sanjay,
The following code example gives a class that behaves in a similar fashion
to a string enumeration. It is a little long winded but I guess could be made
into some sort of template if required.
I hope you find it useful.
Regards,
Phil
using System;
using System.Diagnostics;
class Test
{
[STAThread]
static void Main(string[] args)
{
HOW_GOOD x = HOW_GOOD.AWESOME;
Console.WriteLine( x );
Debug.Assert( HOW_GOOD.AWESOME != HOW_GOOD.TERRIBLE );
Debug.Assert( x == HOW_GOOD.AWESOME );
HOW_GOOD y = (HOW_GOOD ) "A";
Console.WriteLine( y );
Console.ReadLine();
}
}
public class HOW_GOOD
{
private HOW_GOOD() {}
public static readonly HOW_GOOD AWESOME = new _AWESOME();
public static readonly HOW_GOOD GREAT = new _GREAT();
public static readonly HOW_GOOD NOT_TOO_BAD = new _NOT_TOO_BAD();
public static readonly HOW_GOOD TERRIBLE = new _TERRIBLE();
private class _AWESOME : HOW_GOOD
{
public override string ToString() { return "A"; }
}
private class _GREAT : HOW_GOOD
{
public override string ToString() { return "G"; }
}
private class _NOT_TOO_BAD : HOW_GOOD
{
public override string ToString() { return "NTB"; }
}
private class _TERRIBLE : HOW_GOOD
{
public override string ToString() { return "T"; }
}
public static explicit operator HOW_GOOD(string s)
{
if( s == AWESOME.ToString() ) return AWESOME;
else if ( s == GREAT.ToString() ) return GREAT;
else if ( s == NOT_TOO_BAD.ToString() ) return NOT_TOO_BAD;
else if ( s == TERRIBLE.ToString() ) return TERRIBLE;
throw new InvalidCastException();
}
}
Sanjay Pais said:
Thanks Rodger,
I actually also managed to achieve the same doing this:
public static class HOW_GOOD
{
static string[] mstrHowGood =
{
"A",
"G",
"NTB",
"T"
};
public static string AWESOME
{
get
{
return mstrHowGood[0];
}
}
public static string GREAT
{
get
{
return mstrHowGood[1];
}
}
public static string NOT_TOO_BAD
{
get
{
return mstrHowGood[2];
}
}
public static string TERRIBLE
{
get
{
return mstrHowGood[2];
}
}
}
But I get an error when I use it as a return type
HOW_GOOD': static types cannot be used as return types
I tried to do this
Public class MyClass
{
public HOW_GOOD HowAreYouDoing(string MyName)
{
return HOW_GOOD.NOT_TOO_BAD;
}
}
Rodger Constandse said:
Hi,
If you just want to define string constants for enhanced readability, you
can do something like this:
public class HOW_GOOD
{
public const string AWESOME = "A";
public const string GREAT = "G";
public const string NOT_TOO_BAD = "NTB";
public const string TERRIBLE = "T";
}
then you can use it like this: Debug.Write(HOW_GOOD.AWESOME);
It is not exaclty the same as an enum, but it may do what you want.
Best regards,
Rodger
Sequence Diagram Editor - Draw sequence diagrams faster
<
http://www.SequenceDiagramEditor.com>