Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if, #else, #endif in C# source code

I've got a sample code from MSDN and I've found code syntax I've never seen before:

namespace Mvc3RemoteVal.Controllers 
{
        public class HomeController : Controller
        {
            IUserDB _repository;

#if  InMemDB
            public HomeController() : this(InMemoryDB.Instance) { }
#else
            public HomeController() : this(new EF_UserRepository()) { }
#endif


            public HomeController(IUserDB repository) 
            {
                _repository = repository;
            }

            [...]
        }

What are those #if, #else, #endif?

And what is #if InMemDB?

What is InMemDB? A variable?

like image 326
ozsenegal Avatar asked Dec 06 '22 23:12

ozsenegal


2 Answers

Those are called preprocessor directives and exist since .NET 1.0. They allow you to define different compilation directives such as InMemDB and the compiler will evaluate or not the block if this variable has been defined. The documentation of the #if directive provides a more in-depth overview.

In order to define a variable you could use the /define compiler option or use the Conditional compilation symbols in the Build tab of the properties of the project in Visual Studio:

alt text

like image 124
Darin Dimitrov Avatar answered Dec 09 '22 13:12

Darin Dimitrov


These are not new features for Framework 4

this are features you can use for development stage and testing: you can declare:

#Define something

and then

#if something

all the code that is in that "if" will be executed. all the code that isn't, won't.

like image 25
Notter Avatar answered Dec 09 '22 13:12

Notter