Tip: it is best practice to only define one class per cs file.
Announcement
You can find all my latest posts on medium.Tip: For consistency, and to make life easier, the cs file’s name should be named after the class’s name.
Let’s say we have a warehouse ordering system…which we breakdown into 3 cs files:
- Program.cs – this is the main starting point of our component, and hence it contains the “Main” method to reflect this. All this will do is create a “Warehouse” object and then apply a non-static method to that object.
- Warehouse.cs – the warehouse class has a constructor, to make it easy to create an object using this class. It also has a method, which in turn instantiates an object belonging to the “item” class.
- Item.cs – this only returns
First let’s create a new project:
Notice the namespace is now the same name as the namespace:
In visual studio, there are 2 ways to create a new cs file, containing the new class.
The first way is done by right clicking on the project:
Second way is just to declare a new object of that class, as if it already existed, and the ide will automatically prompt you to create a new class (when you see and then click on the blue squigly line):
Creating a new class, will automtically result in a new cs file created, hence vs2013 automatically carries out best practice for you:
Notice also, that it is also created in the same namespace as the main program.
Now I create the various classes:
The content of the Program.cs file is:
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleOOP
{
class Program
{
static void Main()
{
Warehouse NewWarehouse = new Warehouse("Manchester");
Item ItemDetails = NewWarehouse.FindandReturnItem(101);
Console.WriteLine("You have ordered: {0}",ItemDetails.ItemName);
Console.ReadLine();
}
}
}
[/csharp]
The content of the Warehouse.cs file is:
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExampleOOP
{
class Warehouse
{
public string WarehouseLocation {get; set;}
public Warehouse (string WarehouseLocation)
{
this.WarehouseLocation = WarehouseLocation;
}
public Item FindandReturnItem(int ItemID)
{
Item RequestedItem = new Item(ItemID);
return RequestedItem;
}
}
}
[/csharp]
The content of the Item.cs file is:
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExampleOOP
{
class Item
{
public int ItemID { get; set; }
public string ItemName { get; set; }
public Item(int ItemID)
{
this.ItemID = ItemID;
this.ItemName = "Microsoft Office 2013";
}
}
}
[/csharp]
Note: for the purpose of this example, I have kept things simple by hardcoding the itemname to to “Microsoft Office 2013”. In reality the item class is likely to query a database.
Here is the VS2013 project files for this:
ExampleOOP