Confusion with C # enumeration and explicit conversion

I have the following listing β†’

public enum SyncStatus { Unavailable = 0, Checking = 5, StartedAspNetDb = 10, FinishedAspNetDb = 20, StartedMatrixDb = 30, FinishedMatrixDb = 40, StartedConnectDb = 50, FinishedConnectDb = 60, StartedCmoDb = 70, FinishedCmoDb = 80, StartedMcpDb = 90, FinishedMcpDb = 100 } 

What am I using here β†’

  SyncInBackground.ReportProgress(SyncStatus.StartedAspNetDb); MergeRepl aspnetdbMergeRepl = new MergeRepl(SystemInformation.ComputerName + "\\SQLEXPRESS", "WWCSTAGE", "aspnetdb", "aspnetdb", "aspnetdb"); aspnetdbMergeRepl.RunDataSync(); SyncInBackground.ReportProgress(SyncStatus.FinishedAspNetDb); SyncInBackground.ReportProgress(SyncStatus.StartedMatrixDb); MergeRepl matrixMergeRepl = new MergeRepl(SystemInformation.ComputerName + "\\SQLEXPRESS", "WWCSTAGE", "MATRIX", "MATRIX", "MATRIX"); matrixMergeRepl.RunDataSync(); SyncInBackground.ReportProgress(SyncStatus.FinishedMatrixDb); SyncInBackground.ReportProgress(SyncStatus.StartedConnectDb); MergeRepl connectMergeRepl = new MergeRepl(SystemInformation.ComputerName + "\\SQLEXPRESS", "WWCSTAGE", "CONNECT", "Connect", "Connect"); connectMergeRepl.RunDataSync(); SyncInBackground.ReportProgress(SyncStatus.FinishedConnectDb); 

I do not understand why, if int is default enum governing type , I need to CAST this line, also β†’

  SyncInBackground.ReportProgress((int)SyncStatus.Checking); 

Forgive my ignorance, I just like to understand why things are not just what they are.

+4
source share
1 answer

There is simply no implicit conversion from an enumeration type to its base type. This makes it difficult to accidentally use an enumeration as its numeric value.

(Likewise, there is no conversion in another way.)

There is an implicit conversion from constant 0 to any type of enumeration, by the way.

Oh, and unboxing from the value of boxed enum to its base type - or vice versa - also works. At least at some point, it really got really distorted in both the CLI specification and the C # specification; it may well be fixed by now :)

EDIT:

Here's an alternative if you just want to use values ​​as numbers:

 public static class SyncStatus { public const int Unavailable = 0; public const int Checking = 5; public const int StartedAspNetDb = 10; public const int FinishedAspNetDb = 20; public const int StartedMatrixDb = 30; public const int FinishedMatrixDb = 40; public const int StartedConnectDb = 50; public const int FinishedConnectDb = 60; public const int StartedCmoDb = 70; public const int FinishedCmoDb = 80; public const int StartedMcpDb = 90; public const int FinishedMcpDb = 100; } 

Alternatively write this method:

 static void ReportProgress(SyncStatus status) { SyncInBackground.ReportProgress((int) status); } 
+10
source

All Articles