Classes and objects
A class is a blueprint. Each new creates a separate object with its own copy of the fields.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
The class describes what every account has (fields) and can do (methods). Objects are the actual accounts. A method call runs the shared code against one particular object, available inside the method as "this".
Code
class Account {
public:
string owner;
double balance = 0;
Account(string owner) : owner(owner) {}
void deposit(double amount) { balance += amount; }
};
int main() {
Account a("Asha");
Account b("Ravi");
a.deposit(500);
b.deposit(120);
cout << a.balance << " " << b.balance << "\n"; // 500 120
}class Account:
def __init__(self, owner: str):
self.owner = owner; self.balance = 0
def deposit(self, amount: float) -> None:
self.balance += amount
a = Account("Asha")
b = Account("Ravi")
a.deposit(500)
b.deposit(120)
print(a.balance, b.balance) # 500 120class Account {
public string Owner;
public decimal Balance;
public Account(string owner) { Owner = owner; }
public void Deposit(decimal amount) { Balance += amount; }
}
var a = new Account("Asha");
var b = new Account("Ravi");
a.Deposit(500);
b.Deposit(120);
Console.WriteLine(a.Balance + " " + b.Balance); // 500 120Tips
- Fields you do not set start at their default: 0 for numbers, null for references, false for bool.
- Two variables can refer to the same object. Two new calls always give two different objects.
In the .NET library
Since C# 9, new() can omit the type when it is known: Account a = new("Asha"). Object initialisers set properties in the same statement: new Account("Asha") { Balance = 100 }.