Classes and Objects
Constructors
A constructor initializes an object when it is created.
Constructors
Constructors.cs
using System;
class Rectangle
{
public int Width;
public int Height;
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int Area()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
int width = ;
Rectangle box = new Rectangle(width, 4);
int area = box.Area();
Console.WriteLine($"width={box.Width}");
Console.WriteLine($"area={area}");
}
}
using System;
class Rectangle
{
public int Width;
public int Height;
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int Area()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
int width = ;
Rectangle box = new Rectangle(width, 4);
int area = box.Area();
Console.WriteLine($"width={box.Width}");
Console.WriteLine($"area={area}");
}
}
using System;
class Rectangle
{
public int Width;
public int Height;
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int Area()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
int width = ;
Rectangle box = new Rectangle(width, 4);
int area = box.Area();
Console.WriteLine($"width={box.Width}");
Console.WriteLine($"area={area}");
}
}
constructor
A constructor runs when `new` creates an object.