I recently branched out into C# written with Visual Studio Express from C++ written with gVIM. I've been told I'll have to unlearn a lot of stuff to really use C# effectively, but here's my question:
In C++ when writing a class or data type, I would have separate files for the class definition and the driver program. I would then #include
the class in the driver program in order to use it. It isn't terribly clear how to do this in Visual Studio Express 2013 and all the tutorials I've looked up have the class definition and the Main() routine in the same file.
I currently have only two files in my solution folder: the driver program p1.cs and the type definition/implementation targetInt.cs. What is the best way to allow p1.cs to work with my targetInt.cs type? Will it simply have access by virtue of being part of the same solution? If so, how to I get around not having a Main() routine in my type definition?
Here is a screenshot of the solution and the error I'm getting when I try to build the solution. I don't get an error for trying to declare a targetInt
object in p1.cs which points to the namespace already being shared.
http://i793.photobucket.com/albums/yy218/tombombodil/solution_zps6a743e2d.png
Let me know if I need to clarify anything.
It's really not terribly complicated, but it is different from C++. So if you have one file that looks something like this:
namespace MyNamespace
{
public class MyClass
{
//...stuff
}
}
And then you want another file with your Main
(which you will for anything more than a trivially simple project), it would look something like this:
using MyNamespace; // unless you use the same namespace for both
namespace SomeOtherNamespace
{
class Program
{
static void Main(string[] args)
{
var c = new MyClass();
// alternatively, without the using statement, you can just fully qualify
// your class name like so:
// var c = new MyNamespace.MyClass();
}
}
}
But do note that the files need to be in the same project. If they are in different projects you can still do it, but you have to add a reference to the project with MyClass
to the project with Program
. What you can't do is just have an orphaned C# file floating around in your solution and expect it to work.