Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Car:
csharp
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the fields and methods, while the other class holds the Main() method (code to be executed)).
- prog2.cs
- prog.cs
prog2.cs
csharp
class Car
{
public string color = "red";
}
prog.cs
csharp
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
Did you notice the
publickeyword? It is called an access modifier, which specifies that thecolorvariable/field ofCaris accessible for other classes as well, such asProgram. You will learn much more about access modifiers and classes/objects in the next chapters.