You may be familiar with the concept of Object Oriented Programming (OOP), a programming practice based on the concept that we take objects and use their properties to organize code. C# is very object oriented and uses object definers called classes. You define functions to execute repeatable code; likewise you define classes to use repeatable objects. Classes contain properties and methods. Take for instance a person and think of one as a object for a moment. What does a person consistently have? A name, eyes, a head, arms, body, legs, etc. What actions can a person do? They can talk, blink, walk etc. If a person were a class, they would have the properties of a head, body, arms, etc. and the methods of walking and talking. An employee perhaps? Name, employee id, division, salary etc. would be the properties. Getting fired would be an action. You may not realize it yet, but ASP.NET mainly uses classes to execute code. Previously we were using SqlDataConnection to connect to a database. SqlDataConnection is a predefined class in ASP.NET. When we had to use SqlDataConnection we had to store it in a new instance:
SqlDataConnection conn = new SqlDataConnection(cs); //where cs is a connection string.This new instance then carries all the properties and methods that the class SqlDataConnection contains. Open() and Close() are methods of the SqlDataConnection class.
Anatomy of a class
Let's continue our example of a person and define a person class. In your solution explorer find the Models directory, right click on it and add a new item. Models typically refer to a group of classes. To add a class, select Code. Then select Class. Name your class before you click add. This will create a C# file containing your class and lay the foundations for starting your class.
When you have made your class, it should look like this:
Like other C# files you have seen before, at the top are dependencies defined and made available for making this class. You can add more dependencies based on what you want to do with your class. For instance, if you wanted your new class to have database functionality you would add:
using System.Data.SqlClient;at the top with the other dependencies.
Classes utilize access modifiers which define how accessible something is in code. I highly recommend you spend some time getting familiar with access modifiers by clicking here. As a first, you'd want your class to be accessible throughout your application so public has already been declared for your class by default.
You should first define properties of a class at the beginning of your class definitions. In our Person class, let's define a name and age:
Convention dictates that properties should be lowercase and start with an underscore( _ ). This Person class has two undefined properties called "name" and "age" and a defined property called "alive". Whenever a new instance of this Person class is called, name and age are undefined but by default their "alive" status set to true. In general, regardless of the programming language in question, properties should be declared private so that the property cannot directly be manipulated. This is important when dealing with large amounts of code where the consequence of an error is too great to be overlooked. Compare:
int comp = 20; Person._age = comp;and
int comp = 20; Person._age == comp;If _age was declared public, then age would be assigned the value of 20. If it was private, then C# would throw an error. If the original intention was to compare instead of assign, then this logical error would be extremely difficult to find. In other words, making properties private adds a layer of protection against development error. To assign values to properties we will have to use fields.
Fields are used to manipuate properties of a class object. They are set to public so they can be accessed anywhere in the code. Fields usually have two properties of their own, get and set. Get retrieves property values. Because properties are private they are inaccessible directly so you need to access their values indirectly through a field, hence why you cannot retrieve the value of a property by just declaring the property itself:
Person._age; //This will throw an error because it is privateSet assigns values to properties. Likewise, because of the private modifier to properties, their values must be assigned indirectly through public fields. By convention, fields start with a capitalized first letter:
Person.Age; //Age is a field that returns the value of _age
C# reservers the word value as a placeholder for the value on the right hand side of the "=" sign when properties are being set by fields.
You may be familiar with defining functions on their own. Methods serve the same purpose. The advantage of methods over functions is that methods are protected within a class against the rest of your code. When naming functions, you must be mindful of the rest of code in case there is another function of the same name; when naming methods, all that you need to be mindful of naming another method within in the same class, not the rest of the code. C# also supports method overloading where multiple methods can share the same name but each of these methods require different return types or the number of arguments must be different or the type of arguments must be different. An example of a class containing methods with method overloading:
New class objects can also start with properties defined outside the class definition. People have names but not always the same name but a name is required. In our Person class, let's say that when a new instance of this class is made it needs a custom value for its name field. It will require a class constructor which look like this:
A constructor simply requires an access modifier, typically public, and the exact name of the class. Using the constructor looks like this:
Person person = new Person("Andrew");
Classes can also inherit the properties, fields, and methods of other classes. Let's take a student for example. A student is also a person with a name and age. Without having to declare again the properties, fields, and methods of the Person class, a Student class can be declared as such:
Using a class
Before you can do anything with your new class, make sure it is included in the file you're working on. That means a using statement is needed at the top of your file before any code is typed. Because our example class is inside the Models directory, the using declaration would be:
IntroClasses is the name of my project and Models is the directory containing my classes.
Remember that you need to declare the type of variable a variable will before you assign a value to it like string, int, bool. When you declare a new instance of a class object, you need to first declare the class the object will use like so:
Person person = new Person();
The parentheses are required and can contain arguments. Because we gave the Person class a constructor for the _name property we need to provide an argument:
Person person = new Person("Angela");
If we wanted to express the properties of a class, first examine the class definitions. In this case the properties are returned by fields:
lbl_something.Text = person.Name; //"Angela"
The class definitions also say properties can be set by fields:
string new_name = "Angel"; person.Name = new_name; lbl_something.Text = person.Name; //"Angel" int curr_age = 20; person.Age = curr_age; new_age = person.Age + 1; //the value is still 20 person.Age = new_age; //the value is now 21
There are methods included in this class including overloaded ones:
person.Hello(); //"Hello" person.Hello("you"); //"Hello you" person.isAlive(); //"Angel is alive"
Let's create a new instance of a student:
Student student = new Student("Daniel"); student.isAlive(); //"Daniel is alive" student.Alive = false; student.isAlive(); //"Daniel is not alive" student.Age = 25; student.Number = "N01234567"; lbl_something.Text = student.Name + "'s number is " + student.Number; //"Daniel's number is N01234567";