Now we've establised what a variable, lets look at one of the key aspects of .Net, and OOP (Object Orientated Programming)... the Class
What is a Class?
Everything in C# and .Net is associated with a Class or an Object. These can be made up of Methods, properties and fields.
An object is an instance of a Class, this is like a wrapper to be able to access the public properties or methods of a class.
Creating a Class
To create a class you need to use the keyword 'class' before your class name.
Lets create our first class, called Car.
Key points of a Class
fields vs properties
These are both key components of a Class, and can be used in different ways.
A field is a variable which is declared directly in a class. Fields are members of their containing class.
A property is a member that provides a flexible mechanism to read, write or compute the data of a private field. See example below:
Properties have a getter and a setter accessors, as you can see in the example, using the get and set functions.
This is where the logic is applied to utilise the private fields (if logic is required) -- see 'GreetingName' property, it returns a computed value of firstName and surName.
If no logic is needed however, we can utilise "automatic properties" which can be used to set and retrieve their value, without any logic applied. We simply see a property accesor, a property type and it's name. The compiler however sees additional code behind the scenes that looked like our first example.
Lets take a look how automatic properties look:
As you can see we've now added 3 new automatic properties which aren't attached to any private fields. This just means we can set the value, and retrieve them without the need for any extra logic, or code.
**Note: this is the most common way of using properties, and the most common way you'll see classes writ
Usage of the automatic properties.
var user = new User();
user.PostalCode = "PO77 T1K";
As you can see they are set in exactly the same way as before, when using private get and set methods (as that's what the compiler is doing behind the scenes anyway).
When should I use a property, when should I use a field.
Fields as a rule of thumb should always be private to the class, and only accessible / manipulated via public properties.
Fields could be used to store constant values, information that could be used by other properties (e.g first name and surname example in the code above). We store them in private fields using get;set; but can then utilise these values and append logic to them to be used elsewhere.
Accessors - public vs private
There are other accessors, but for this tutorial we'll concentrate on public and private (as these are the two most commonly used).
Private - means that only properties and methods within the class itself can access & utilise the item (class, property, field)."
Public - means its accessbile to any other class or method.
Hope this has all made some sense, it can be quite daunting to coding newbies.
Constructors
No, we're not talking about building sites or construction work , a constructor is how we tell the compiler how to create a new instance of our class / object.
Example:
// Creating a new User constructor.
public class User {
public string Name {get;set;}
public int Age {get;set}
public Datetime DOB {get;set;}
public User (Datetime dob){
DOB = dob;
Age = (DateTime.Now - DOB).Days /365;
}
}
//create a new user instance
var user1 = new User(new DateTime(1965,2,25));
user1.Name = "Gary Phillips";
//write out the users computed age.
Console.WriteLine(user1.Age);
So what have we done here?
We have created a User class, that has a couple of properties, and we've created a constructor.
The constructor accepts a DateTime object of Date of Birth, and this is then assigned to the DOB user class property.
We then calculate the Age property value based on today's date - date of birth divided by 365 days in a year.
Constructors are perfect for setting up these kind of things. You create a new instance and have the constructor setup a lot of properties for you if feasible.
There are pros and cons of this. The pros are like I say automated value assignment, and you can assume / feel confident that properties have a value when you try to use the object later on.
However this is not always the 5perfect situation. You may want the property value to be live and not set at time of creation.
As an example:
Say we wanted to know your exact age and update a ticker. By using the constructor method the value would only be set once at creation time and then it would have to be updated manually via code.
However if we wanted our scenario we could utilise a fat arrow =>
which will make the property read only, and return a value, which in our case could calculate the date like so.
public int Age => (Datetime.Now-this.DOB)/365;
//or the readonly traditional way
public int Age {
get{
(Datetime.Now-this.DOB)/365;
}
}
You can see the traditional way we haven't gave the property a set function setter. Thjs property therefore automatically becomes a readonly method. Meaning that if we were to attempt to set its value In our code we would receive a build error upon trying to build and compile the code. Some IDEs would display a error (usually a squiggly line) under the code illustrating the code would error upon building.
Top comments (0)