Concept of a Class
A class is simply an abstract model used to define a new data types. A class may contain any combination of encapsulated data (fields or member variables), operations that can be performed on data (methods) and accessors to data (properties). For example, there is a class String in the System namespace of .Net Framework Class Library (FCL). This contains an array of characters (data) and provide different operations (methods) that can be applied to its data like ToLowerCase(), Trime(), Substring(), etc. It also has some properties like Length (used to find the length of the string).
A class in C# is declared using the keyword class and its members are enclosed in parenthesis
where MyClass is the name of class or new data type that we are defining here.
Objects
As mentioned above, a class is an abstract model. An object is the concrete realization or instance built on the model specified by the class. An object is created in the memory using the keyword 'new' and is referenced by an identifier called a "reference".
In the line above, we made an object of type MyClass which is referenced by an identifier myObjectReference.
The difference between classes and implicit data types is that objects are reference types (passed by reference) while implicit data types are value type (passed by making a copy). Also, objects are created at the heap while implicit data types are stored on stack.
Fields
fields are the data contained in the class. Fields may be implicit data types, objects of some other class, enumerations, structs or delegates. In the example below, we define a class named Student containing a student's name, age marks in maths, mark in English, marks in science, total marks, obtained marks and a percentage.
you can also initialize the fields with the initial values as we did in totalmarks in the example above. If you don't initialized with their default values. Default values for different data types are shown below.
Methods
Methods are the operations performed on the data, A method may take some input values through its parameters and may return a value of a particular data type. The signature of the method takes the form
For example,
Here, we defined a method name FindSum which takes two parameters of int type (num1 and num2) and returns a value of type int using the keyword return. if a method does not return anything, its return type would be void. A method can also optionally take no parameter (a parameterless method)