官术网_书友最值得收藏!

Writing a simple class

Now let's create our first class. Let's imagine that we are developing some software for a bank. Our application should keep track of the bank's customers and their bank accounts, and perform some basic actions on those bank accounts. As we are going to design our application using C#, we have to think of our application in an object-oriented way. Some objects that we will need for this application could be a customer object, a bank account object, and other objects. So, to make blueprints of these objects, we have to create a Customer class and a BankAccount class, as well as the other classes that we will need. Let's first create the Customer class using the following code:

class Customer
{
public string firstName;
public string lastName;
public string phoneNumber;
public string emailAddress;

public string GetFullName()
{
        return firstName + " " + lastName;
}
}

We started with the class keyword and then the name of the class, which is Customer. After that, we added the class body inside curly braces, {}. The variables that the class has are firstName, lastName, phoneNumber, and emailAddress. The class also has a method called GetFullName(), which uses the firstName and the lastName fields to prepare the full name and return it.

Now let's create a BankAccount class using the following code:

class BankAccount {
public string bankAccountNumber;
public string bankAccountOwnerName;
public double amount;
public datetime openningDate;

public string Credit(){
// Amount credited
}

public string Debit(){
// Amount debited
}
}

Here, we can see that we have followed a similar approach to create a class. We have used the class keyword and then the name of the BankAccount class . After the name, we started the class body with an opening curly brace and entered fields such as bankAccountNumber, bankAccountOwnerName, amount, and openningDate, followed by two methods, Credit and Debit. By placing a closing curly brace, we end the class body.

For now, don't get worried about keywords such as publicwe will learn about these keywords later in the book when we talk about access specifiers.

主站蜘蛛池模板: 邓州市| 丹阳市| 浏阳市| 蕉岭县| 广东省| 崇礼县| 织金县| 方正县| 清涧县| 金乡县| 基隆市| 杭锦后旗| 龙口市| 石首市| 荣成市| 长葛市| 鄂托克前旗| 高邑县| 浦东新区| 沛县| 万年县| 遵义市| 宜丰县| 白山市| 绥中县| 呼和浩特市| 梁山县| 广宗县| 宕昌县| 沂水县| 南通市| 巩留县| 广灵县| 观塘区| 汤阴县| 岳普湖县| 兴山县| 灵武市| 莱芜市| 余庆县| 襄垣县|