Classes are used to model real-world objects in programming
State (fields, properties)
Behavior (methods, operations)
Classes describe the structure of object
Objects are particular instance of a class
// class
public class Person
{
// Model the person
}
// object (use the class for creating instance)
Person person = new Person();
class Person
{
// State
public string Name { get; set; }
// Behavior
public void Speak()
{
Console.WriteLine($"Hello I'm {this.Name}");
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "John";
person.Speak(); // Hello, I'm John
}
}
Class definition consists of:
Inherited class or implemented interface
Fields are data members defined inside a class
internal object state
could have any access modifier
but they must be always private
class Person
{
private string firstName;
private string lastName;
private int age;
}
Two types
const - compile-time
Replaced during compilation
Contain only values known at compile time
readonly - runtime
Assigned once at object creation
Can contain values, calculated at runtime
class Person
{
public void PrintName()
{
Console.WriteLine("Some name here");
}
}
// Using it
Person person = new Person();
person.PrintName();
class Person
{
private string firstName;
private string lastName;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public string FullName
{
get
{
return this.firstName + this.lastName;
}
}
}
class Person
{
public Person(string name)
{
this.FullName = name;
}
public string FullName { get; set; }
}