mirkaim
mirkaim

Reputation: 314

Visual Studio Express 2013 - Create separate c# code file?

The VS 2013 Express forum doesn't seem to exist at Microsoft so I'd like to ask here..

I am using Microsoft VS Express 2013 to create a C# project. I'd like to be able to add a whatever.cs file to the project so that I can put extra functions there instead of in the default Program.cs file. Back in the old days, we could import code files in C by using a #include but C# in the Visual Studio doesn't seem to do this.

I have been able to successfully add a .cs file, create a class within it, and then instantiate the class and call it's methods from within Program.cs but I'd rather not have to instantiate a variable and have to call functions like something.MyFunction() just to execute some code that exists in another file.

Is this even possible? If not, does anybody know why? I always like the #include in C. You could keep things nice and neat.

Upvotes: 1

Views: 2719

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61369

Files added to a Visual C# project are automatically "included" in every other file within that namespace. You do not need a using statement unless you change the namespace. Because of this, there is no equivalent of the "#include" directive from C/C++.

Now to handle your use case. C# is inherently object-oriented. It is not expected that you create a million functions and call them individually (like you do in C). So, if you want to use multiple files (and you should!) you have a few options:

  1. Create a normal class (as you have already done) and instantiate it to call its methods. This is the preferred method, and you should be able to come up with plenty of classes for your program that make sense.

  2. Create a static class. These don't have to be instantiated (you access them like MyStaticClass.MyFunc(); ). These are often used as "helper" classes. In general, use sparingly as they are hard to unit test/dependency inject.

  3. Mark your class as partial. This allows you to define the same class over multiple .cs files. Again, this should be used sparingly (see Jon Skeet's answer: https://stackoverflow.com/a/2895068/1783619)

Upvotes: 2

Related Questions