C# Classes
In C#, classes are one of the fundamental building blocks of object-oriented programming (OOP).
They allow you to define blueprints for objects, encapsulate data and behavior, and organize code in a modular and reusable way. Here's a basic overview of creating and using classes in C#.
Class Declaration
You declare a class using the class
keyword, followed by the class name. The class body is enclosed in curly braces {}
public class MyClass
{
// Class members (fields, properties, methods, etc.) go here
}
Class Members
Fields: Fields are variables declared within a class.
public class MyClass
{
// Field
public int myField;
}
Properties: Properties provide a way to encapsulate private fields and control access to them.
public class MyClass
{
// Private field
private int myField;
// Property
public int MyProperty
{
get { return myField; }
set { myField = value; }
}
}
Methods: Methods are functions defined within a class.
public class MyClass
{
// Method
public void MyMethod()
{
// Method body
}
}