C# include?

Started by
6 comments, last by PhillipHamlyn 11 years ago

Is there a way to do a C-style #include in C#?

The situation is that I'm working on an application that compiles to two different but related products from the same branch of the same codebase using buildtime shenanigans It is all working but I was thinking some things would be cleaner if I could just conditionally include code into a particular file based on a preprocessor definition.

Advertisement
There aren't #includes in C# (one of the various reasons compile time is so fast).

You might be able to use partial classes or extension methods depending on what you're trying to accomplish.

Nope. No #include functionality in C#.

One possible solution would be partial classes. You could collect the common method implementations for a class into one file. Then have the product-specific method implementations in two separate files. Specify file 'A' in product 'A's project and file 'B' in project 'B's project. Tying the files together with the partial keyword at least allows you to break out the product-specific implementations into separate files.

Your mileage may vary.

The main limitation of partial classes is that all of the files have to be in the same project at compile time (filename and folder don't matter though). If they're in separate projects, each output assembly gets a separate class.

Extension methods can be defined in a different assembly than the class they extend, but they can only access public members of that class.

You can use #if/#endif in C# for using preprocessor directives.

You can also add files as a link, so you keep the file in a common directory and any number of projects can include the file as a link which means they'll all share the same C# file, but it will be compiled into all the projects. As long as the projects don't reference each other you should be fine (if the projects reference each other, you're likely to get an error for having the same type compiled twice).

You basically just have to add the .cs file to the project, no need for #include's.

I wouldn't recommend it, but you can use the C/C++ preprocessor to process C# files before sending them to the C# compiler. Maybe mark them with a different extension, say .cspp, and then send each through a pre-compiler step that runs them through the preprocessor which spits out a temp file that you send to the C# compiler in its place.

This will give you all the C/C++ preprocessor abilities including #define macros and #includes.

Note this applies to source files in any language, not just C#.

But again, I would not recommend this. Unless you have a very good reason, like macro tables.

C# doesn't need includes becuase shared source files can be added as Linked Files in visual studio, or if rellay needed, compile them as libraries and add the project reference.

This topic is closed to new replies.

Advertisement