Class Methods, Properties and Constructor Methods

The purpose for creating a special class to represent data is to contain all of the other data that’s associated with it.

A field is a variable that belongs to the class. It’s sometimes called an instance field.

Classes have both static fields and instance fields. A static field belongs to the class definition while an instance field belongs to each instance of the class.

You declare fields as members of the classes.

Fields should generally be kept private to the class and then only made available to the rest of the application using accessor methods and modifier methods.

The accessor method is called the getter and the modifier method is called the setter.

get { return item;}

set { item = value;}

Above verbose approach to declaring properties, declaring explicit get and set methods. The reason to do this is if you want to apply any custom logic.

C# makes it easy – if all you want to do is encapsulate the data, and create a default get and set method,

Public double price  {get; set;}

——

When you declare your own custom class… it automatically extended from the class called object.   This relationship is sometimes called the base class and the derived class [superclass and the subclass]   The derived / subclass inherits from the base class

Every object in C# has a ToString method, because every class is extended from the object class. And this method is called automatically. Whenever you take an object and pass it somewhere that’s expecting a string.

a Constructor method is a special kind of method that has the same name as the class that it’s defined as a part of and that’s used to create an instance of the class. When you create your own custom classes, you don’t have to explicitly declare a constructor method, but if you don’t, a constructor method is generated for you by the compiler. It doesn’t receive any arguments or parameters and it’s sometimes called a no arguments Constructor, but you can create your own custom constructor methods too.

There’s one very important rule. If you create a custom constructor method, your class must have a no arguments constructor method that’s explicitly declared. You can have multiple constructor methods as long as they differ in either the number of parameters or the data types of the parameters

custom constructor methods make it very easy to create custom classes that you can instantiate with values in single statements. And there are other ways of using custom constructor methods in your code to make your application easier to write and easier to maintain.