How to create and use classes in C#?

To create a class in C#, you can follow these steps:

  1. Define a class using the keyword “class”, and then write the class members within the curly braces.
public class MyClass
{
    // 类的成员
}
  1. Define fields, properties, methods, and other members within a class.
public class MyClass
{
    public int MyField;
    
    public void MyMethod()
    {
        // 方法实现
    }
}
  1. This class can be instantiated in other classes and its members can be called.
MyClass myObject = new MyClass();
myObject.MyField = 10;
myObject.MyMethod();
  1. You can initialize an instance of a class by using a constructor.
public class MyClass
{
    public int MyField;
    
    public MyClass(int value)
    {
        MyField = value;
    }
}
  1. Using inheritance to create subclasses is possible.
public class MySubClass : MyClass
{
    public void MySubMethod()
    {
        // 子类方法实现
    }
}
  1. Access modifiers such as public, private, and protected can be used to control the accessibility of a class’s members.

These are the basic steps to create and use classes in C#, with which you can define your own class and use its members.

bannerAds