C# Classes & Objects
Objectives
- What is Classes & Objects ?
- How to creating classes & objects
- Constructors
- Properties
- Methods within classes
What are Classes & Objects?
Class is a blueprint for creating objects.
It defines the structure and behavior of objects by encapsulating data (fields) and methods (functions) that operate on the data.
Object is an instance of a class.
Objects are created from classes and can interact with other objects and the environment through methods and properties.
Creating Classes & Objects:
To create class use the "class" keyword followed by the class name and its body enclosed in curly braces {}.
Within the class body, you define fields, properties, constructors, and methods.
public class Person
{
// Fields
public string Name;
public int Age;
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
Creating Objects:
To create an object of a class, you can use the new keyword followed by the class name and parentheses () if invoking a parameterless constructor, or with arguments if invoking a parameterized constructor.
Person person1 = new Person("John", 30);
Constructors:
Constructors is special methods in a class used for initializing objects.
Constructors are invoked automatically when objects are created using the new keyword.
public class Person
{
public string Name;
public int Age;
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Properties:
Properties are members of a class that encapsulate fields, providing controlled access to them.
They allow you to get and set the values of private fields using get and set accessors.
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
Methods within Classes:
Methods in a class define the behavior or actions that objects of the class can perform.
They can operate on the class's fields, properties, and other objects.
Methods are declared within the class body and can have parameters and return values.
Example:
public class Calculator
{
public int Add(int num1, int num2)
{
return num1 + num2;
}
}