C # Ruby Symbol Equivalent

I am developing a small C # application for fun. I like this language, but something bothers me ...

Is there a way to make #define (C mode) or symbol (ruby mode).

The ruby ​​symbol is very useful. It’s just some name preceded by β€œ:” (example β€œ: guy”), each character is unique and can be used by anyone where in the code.

In my case, I want to send a flag (connect or disconnect) to a function.

What is the most elegant C # way to do this?

Here is what I would like to do:

BgWorker.RunWorkersAsync(:connect) //... private void BgWorker_DoWork(object sender, DoWorkEventArgs e) { if (e.Arguement == :connect) //Do the job } 

At this point, my favorite answer is the enum solution;)

+7
c # ruby symbols
source share
4 answers

In your case, sending a flag can be done using an enumeration ...

 public enum Message { Connect, Disconnect } public void Action(Message msg) { switch(msg) { case Message.Connect: //do connect here break; case Message.Disconnect: //disconnect break; default: //Fail! break; } } 
+6
source share

You can use the string constant:

 public const string Guy = "guy"; 

In fact, strings in .NET are special. If you declare two string variables with the same value, they actually point to the same object:

 string a = "guy"; string b = "guy"; Console.WriteLine(object.ReferenceEquals(a, b)); // prints True 
+3
source share

C # does not support C-style macros, although it still has #define. For reasons of this, take a look at the csharp FAQ blog on msdn.

If your flag is for conditional compilation purposes, you can still do this:

 #define MY_FLAG #if MY_FLAG //do something #endif 

But if not, then what you are describing is a configuration parameter and may need to be stored in a class variable or configuration file instead of a macro.

+2
source share

Like @Darin, but I often create a Defs class in my project to put all such constants so that they can be accessed from anywhere.

 class Program { static void Main(string[] args) { string s = Defs.pi; } } class Defs { public const int Val = 5; public const string pi = "3.1459"; } 
0
source share

All Articles