Reputation: 11
I hope I can explain what I mean.
namespace BackgroundJob
{
public static class Konstanten
{
public const string closed = "closed";
public const string error = "error";
public static readonly JobStatus jobStatus = new JobStatus();
}
private class JobStatus
{
public string closed { get { return "closed"; } }
public string error { get { return "error"; } }
}
}
I thought it would be better group the constants in case they are used. This is the reason why I created the class "JobStatus". I use the constants in a switch case statements. This works fine:
case Konstanten.error:
but this causes an error:
case Konstanten.jobStatus.error:
ErrorMessage: "A constant value is expected"
Can you tell me how to solve this problem?
Upvotes: 1
Views: 95
Reputation: 29274
This is definately a case where you need enum
constants. Here is how to use them:
public enum JobStatus
{
[Description("Job is Closed")]
Closed,
[Description("Job Had Error")]
Error
}
public class Job
{
public JobStatus Status { get; set; }
public void Report()
{
switch(Status)
{
case JobStatus.Closed:
// handle closed
break;
case JobStatus.Error:
// handle error
break;
}
Console.WriteLine( Status.GetDescription() );
// Prints "Job Had Error"
}
}
class Program
{
static void Main(string[] args)
{
var job=new Job();
job.Status=JobStatus.Error;
job.Report();
}
}
public static class Extensions
{
public static string GetDescription(this Enum value)
{
Type type=value.GetType();
var field=type.GetField(value.ToString());
if(field!=null)
{
var attr=field.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
if(attr.Length>0)
{
return attr[0].Description;
}
}
return string.Empty;
}
}
I have included an extension method to extract the DescriptionAttribute
defined for each job status value. You need to include using System.ComponentModel;
to use this attribute.
Upvotes: 0
Reputation: 11607
You should try and mentally separate the states of the program from the actual values you are trying to use.
The first thing is just using an enum, representing the finite number of states. That should already suffice for many many uses you may have.
In the extreme, you'll maybe need a parser and renderer of those states to strings. This is easily done with the Enum.Parse() and e.ToString() methods.
There is really no need to keep constant strings around, like "closed" and "error". Get rid of them!
Upvotes: 1
Reputation: 727047
but this causes an error:
case Konstanten.jobStatus.error:
This is because the error
member of the class JobStatus
is a property, not a compile-time constant, and because JobStatus jobStatus
is an object created at runtime.
If you change error
to a const
, like this,
public const string error = "error";
you would be able to write
case JobStatus.error:
and reference the constant directly. Your original expression case Konstanten.jobStatus.error:
would remain broken, however, because Konstanten.jobStatus
is an object.
Upvotes: 2