How to use class and object in C#
I am sure you heard of class and object and you might be wondering what is a class. What is an object? What is the difference between a class and an object? In this article, we will discuss this and more.
In this article, we will delve into the fundamental concepts of class and object in C#. Exploring the essence of a class, the essence of an object, and uncovering the distinctions between them, we aim to provide you with a comprehensive understanding of these core components in C# programming.
But before we start, let’s relax with two jokes (good or bad, you be the judge):
Why are programmers single?
Because they treat women like Objects.
Why do programmers have beautiful girlfriends?
Because they have Class.
Classes and objects are specific to Object-Oriented Programming (OOP). So before going into what is a class and what is an object we should cover what is OOP.
What is Object-Oriented Programming?
Object-Oriented Programming, widely known as OOP is a programming paradigm. OOP uses objects and interactions of objects for building applications or software. We won’t go into many details about OOP, as we are going to cover this in a more detailed article in the future. What is worth mentioning at this point are four pillars of OOP:
- Encapsulation is also known as hiding information. Provides the users only with what they need. At the same time, it doesn’t provide internal details about the implementation. Achieve encapsulation by restricting access to public methods.
- Abstraction – in a nutshell, working with something you know how to use without knowing about the implementation.
- Inheritance – allows a class to inherit the behavior and/or characteristics of another more generic class.
- Polymorphism – treat objects of a derived class as objects of its base class. Polymorphism resembles abstraction but it overrides methods in derived classes. Long story short, you can access objects of different types through the same interface.
What is an object?
In a short sentence that will get you through an interview: An object is an instance of a class. But what does this mean? Objects are data structures that contain data, in the form of fields (or attributes) and code, in the form of methods in C#’s case.
All objects have the following three:
- State of an object – The state or attributes are an object’s built-in characteristics or properties. Eg. a car has the size, model, brand, etc.
- The behavior of the object – The behavior or operations of an object is its predefined methods. Eg. a car drives, opens doors, etc. We can achieve this in C# by using methods.
- Object identity – Each object is uniquely identifiable. Eg. a car can not become a dog or a cat.
What is a class?
Wikipedia helps us with a definition of a class. A class is an extensible program code template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). More simplified, a class is a blueprint or a set of instructions to build a specific object type. The class determines how the object will behave and what it will contain.
These are the elements within a class:
- Class declaration – here we declare the name of the class. Eg:
public class Person
- Class body – every class has a single class body. The body of the class in C# is enclosed in curly brackets “”. All of the other elements enumerated below are part of the class body
public class Person
{
// class body
}
- Constructor – it prepares the new object for use. Can accept arguments that the constructor uses to set fields, properties, or call methods in the class.
public class Person
{
public Person()
{
// this is a class constructor
}
}
- Fields – these are variables declared inside the class (also known as member variables).
public class Person
{
// this is a field
private string name;
}
- Properties – this is where we describe the characteristics of a class. A property works like a class field. The purpose of a property is to set and receive the values of a field.
public class Person
{
// this is a property
private string Name { get; set; }
}
- Methods – named blocks of code that contain a series of statements. The program executes these statements by calling the method and specifying any required method arguments.
public class Person
{
// this is a method
public string GetFullName()
{
}
}
Here is an example of a class defining a person:
public class Person
{
private readonly int age;
public Person(int age)
{
this.age = age;
if (this.age >= 21)
{
HasLegalAge = true;
}
}
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool HasLegalAge { get; }
public string GetFullName()
{
return $"{FirstName} {LastName}";
}
}
5 Questions about classes and objects you might get in an interview
Subscribe to Relaxed Coder and get an email with 5 Questions about classes and objects you might get in an interview.
Organizing classes
Classes in C# have to be declared in files with the extension .cs. One or multiple classes can be stored inside a .cs file, but I highly recommend having them on file for one class. Following on our example from above, we should have only one file called Person.cs, and inside this file to have the declaration of the person class.
When we have many classes that have a logical connection with each other, we should look towards grouping them into namespaces. Namespaces in C# are named groups of classes. When we want to use a class from another namespace we will need the using directives. These using directives will be on the first lines of the class file.
Here is an example of the person class that is part of a namespace:
namespace Demo.Domain
{
public class Person
{
...
}
}
Now let’s assume we need to access the Person class from another class that is part of a different namespace:
using Demo.Domain;
namespace Demo.BusinessLogic
{
public class PersonBusinessLogic
{
public string GetPersonFullName()
{
var person = new Person(30)
{
FirstName = "John",
LastName = "Doe"
};
return person.GetFullName();
}
}
}
You can see that the first thing we did was to use the Person class namespace. This way we have access to all the classes that are part of the Demo.Domain namespace.
Modifiers and access levels
Access modifiers are: public, private, protected, and internal. Access modifiers can be used for class declaration, fields, properties, and methods. Based on the access modifiers we can control the access (or the visibility) to specific elements of the class.
- Public Access Level – we are telling the compiler that this element can be accessed from every class from the current namespace. This is the least restricted access level in C#.
- Private Access Level – this access modifier is used to indicate that the element cannot be accessed from any other class. This is the default access level and is the most restrictive level of visibility.
- Internal access level – this modifier is used to limit the access to class elements only to files from the same assembly. An assembly is a .dll or .exe created by compiling one or more .cs files in a single compilation.
- Protected access level – this modifier is used to specify that access is limited to the containing type or types derived from the containing class, so the type or member can only be accessed by code in the same class or a derived class.
Naming classes and best practices
How you name your classes is up to you. You must follow certain rules defined in the C# language specification:
- names can contain the letters a-z, A-Z, the digits 0-9 as well as the character ‘_’.
- the first character of the name must be a letter. The underscore is also a legal first character.
- C# keywords can’t be used as class names (eg. base, char, default, int, object, this, null, etc.)
Besides the rules defined by the C# language specification, here are some recommendations to help you name your classes:
- Meaningful names – the name of the class should tell you why it exists, what it does, and how it’s used. Please be aware that if you feel the need to add a comment alongside the class declaration, most likely the name does not reveal the intent of the class.
- Use Camel Case as best code practices when naming your classes. Do not use random Capitals throughout your class names. Eg.
// good
public class PersonCategory
// bad
public class PeRsoncAtegory
- Pronounceable names – the code you are writing should be like an open book. When part of a developers team, you will not write code just for yourself. Somebody else will look over your code, he or she should be able to read it and understand it
Apart from best practices regarding class naming, here are a few more to help you write clean and easy-to-read classes:
- Keep the class size small – you must segregate classes into small blocks which has a single responsibility function only. When reading a class body you should avoid having it so long you have to scroll forever.
- Start with a private access modifier when declaring fields, properties, and methods and make visible outside the class only the elements that need to be visible.
- Try not to produce unused code. If you implemented a method in a class and you don’t use it anywhere in your application, just go ahead and delete it. Also don’t use comments to comment on unused code, as I said, hit that delete button.
I hope you enjoyed this post and found it useful. If you have any questions or suggestions for improving this post please let me know in the comments section below.