C# define question?

I want to be able to do something like this

#if WINDOWS
#define CONNECTIONTYPE OdbcConnection
#else
#define CONNECTIONTYPE MySqlConnection
#endif

Then later I could have a function such as

CONNECTIONTYPE connection = new CONNECTIONTYPE ( "blahblah" );

But I have read that in C# you cannot define things as variables...

Does anyone know of any other way to do what I am trying to accomplish


Answer this question

C# define question?

  • RennySchweiger

    Thanks guys. After a bit of research on factory classes, I was able to get this working.

  • rpjimenez

    You could achieve something similar using the Conditional Attribute - google for many examples.

    However, your actual implementation requirement lends itself to a factory class solution as mentioned by the previous poster.



  • mfroman

    I think this is where you should use the Factory Pattern.

    Do this (let's consider Connection to be a base interface/class of both OdbcConnection and MySqlConnection:
    Connection connection = ConnectionFactory.CreateConnection("blahblah");
    Where ConnectionFactory is:
    public static class ConnectionFactory
    {
    public static Connection CreateConnection(string connectionString)
    {
    #if WINDOWS
    return new OdbcConnection(connectionString);
    #else
    return new MySqlConnection(connectionString);
    #endif
    }
    }
    This is only a good solution if you do not reference the assembly containing the MySqlConnection type in the Windows version of your product and vice versa.
    If you reference both assemblies, use an if clause with the Environment class to switch between creating an OdbcConnection or a MySqlConnection.

    Hope this helps.


  • C# define question?