Introduction to C# Classes

Hi Everyone! Hope you all are doing great. We always love when you keep coming back for what we have to offer. Today, I am going to give you a Introduction to C# Classes. We have already seen Introduction to Data Types in C# which includes boolean, integer, char and double. However, if you want to make complex custom type, you can make use of classes. I'll give you a brief introduction to classes so you don't have to go anywhere to find information regarding classes in C#. Let's hop on the board and dive in the details of classes.

Introduction to C# Classes

  • Class in C# is referred as a blueprint of complex data type that describes the behavior and data of type.
  • If you want to create complex custom type, we use class. What do I mean by complex custom type?
  • Suppose you want to store a number 123, you can store it easily in an integer variable.
  • However, if you want to store the customer's information, you can use classes like what kind of information customer has, what is his first and last name, his email ID, phone number and age etc.
  • By using a built-in fields we can create a class.
  • Fields of class define the class data and methods define the behavior of the class.
  • When we create customer class, it not only contains the data, it can also do certain things like save the customer to the data base, print the customer full name etc.
  • So, class has state and behavior, state is nothing but data and behavior is nothing but what the class is capable of doing.
How to Create a Class
In order to create a class we use a class keyword followed by the name of the class and members of class are enclosed by curly brackets. Let's look at an example which will make things clear. Example 1 Following figure shows the complete explanation of classes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Customer
{
    string _firstName;
    string _lastName;

    public Customer (string FirstName, string LastName)
{
        this._firstName = FirstName;
      this._lastName = LastName;
}
    public void PrintFullName()
    {
        Console.WriteLine("Full Name = {0}", this._firstName +" "+ this._lastName);
    }
    ~Customer()
    {
        //clean up code
    }
    
}
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer C1 = new Customer("Adnan", "Network");
            C1.PrintFullName();
        }
    }
}
  • In the above example first name and last name of the customer is stored in a string which represents the state of the class.
  • To initialize these fields a class can also have an constructor.
  • A constructor will have a same name as that of your class.
  • We make constructor public which is an access modifier.
  • Constructors are basically used to initialize the class fields.
  • Then we pass two parameters into this constructor which are string FirstName and string LastName.
  • Constructor doesn't return a value but it can take parameters.
  • Then we use constructor to initialize these class fields i.e _firstname and _lastname.
  • This field _firstname is equal to the parameter FirstName and the field _lastname is equal to the parameter LastName.
  • Then we put "this" keyword before firstName and lastName which is used to define the instance of classes also referred as objects.
  • So, basically we are using constructor to initialize the class fields with parameters that are passing into the constructor.
  • In the next step we add a behavior which allows the class to do something.
  • We want to print the full name of the customer. This is called the method of the class which tells the behavior of the class.
  • So far, we have created constructor, two fields and a methods for the class.
  • In the next step we call the destructor of the class.
  • Destructor will have the same name as that of the class but it doesn't take parameters and doesn't have a return type.
  • Usually in C# we don't require destructors.
  • We use destructors to clean up the resources your class was holding on to during its life time.
  • We don't need to call the destructors, they are automatically called by the garbage collector.
  • In the next step we make use of class in our main method.
  • In this step we create instance C1 of class Customer with using the keyword "new".
  • This instance is also called the object of the class. Instances and Objects are used interchangeably.
  • Then we call FirstName and LastName of the customer. When we put FirstName as Adnan, it will pass through the parameter (string FirstName) of the constructor. And put second name as Network that will pass through the parameter(string LastName) of the constructor.
  • Constructors are called automatically when you create instance of class.
  • Also, constructors are not mandatory to use, if you don't provide a constructor, .NET framework will automatically provide a default parameter less constructor.
  • In the next step we print the full name of the customer.
Output Output of the above program will be like below. That's all for today. I hope you have got a clear idea about class, constructor and destructor used in C#. However, if still you feel any doubt or have any question you can ask me in the question below. I'll be happy to help you in this regard according to best of my expertise. Stay tuned!

Introduction to Data types in C#

Hey Guys! I hope you all are doing great. Today, I am going to give a detailed Introduction to Data types in C#. It's our 3rd tutorial in C# series & it's a theoretical tutorial so you just need to read it once. I'll try to cover every aspect related to Data types in C# so you get a clear picture of what are data types and why we need them? So, let's get started with Introduction to Data types in C#:

Introduction to Data types in C#

  • Data Types in C# are used to inform the compiler about the type, size & nature of data that can be stored in a variable.
  • Whenever we need to declare a variable, we need to inform the compiler about the data size & type of the variable.
  • There are 3 types of data types available in C# programming, which are:
      1. Value Data Type
      2. Pointer Data Type
      3. Reference Data Type
  • Here's a Flow Diagram of C# Data types for better understanding.
  • Let's discuss these C# data types one by one in detail:
1. Value Data Types
  • Value Data Type Variable is the simplest variable in C#, to which we can assign a value directly and they save this value on the stack, so it's not cleared by Garbage Collector.
  • Each variable stores its data in a separate memory so we can't assign a single memory to multiple variables, although we can update their data quite easily.
  • Value data types are further divided into two types, named:
    • Predefined data types.
    • User defined data types.
A. Predefined Value Data Types: These Value Data Types are predefined in C# i.e. bool, int, float, decimal, char etc.
  • Bool: a short form of Boolean, contains two values i.e. true or false.
  • Int: a short form of integer.
  • Char: a short form of character, which is used to store alphabets.
  • Float: is used to store a floating point number i.e. number with decimal values.
  • Here's a table showing Memory Size & Range of these Data Types in C#:
  B. User Defined Value Data Types: User can also create customized data types in C# using existing data types. i.e. structure or enumerations etc.
  • Enumerations This value data type contains set of related named constants which are called as enumerator list. The "enum" is used to declare the word enumerations.
  • Structure or struct is referred as a grouped list of variables that can be placed under one name in memory. It is same like a "Class" in the reference type.
Don't worry about these concepts, we will cover them on by one in our coming lectures.
2. Pointer Data Type
  • The pointer, also called as indicator or locator, is a data type in C# that points towards the memory address of a data, we need to use ( * ) in its declaration.
  • The pointer in C# can only hold the memory address of arrays and value types i.e. int, char, float etc.
  • No conversion is allowed between pointer types and objects.
  • However, conversion between two different pointer types is allowed, you can also convert between pointers and integral types.
  • You can also point multiple pointers in same data type.
3. Reference Data Types
  • Reference data types in C# don't consist of actual data, instead they point towards the reference to the data stored in a variable, it saves data in the heap.
  • In reference data types, it's possible for two variable to reference to the same object.
  • Reference Data Types are further divided into two types:
A. Predefined Reference Data Types: contain objects, strings etc.
  • String is a sequence of finite characters which can contain spaces and number. Total number of characters in the string refers to the string length. i.e. "I need 20 dollars" is a string.
  • Object is referred as a block of memory that executes according to the blueprint.
B. User Defined Reference Data Types: contain classes, interface, etc.

Nullable Data Types

  • In C# data types, the most commonly used data types are Value Types & Reference Types. Pointer types are not used that much.
  • In above discussion, we have seen that:
    • Value Data Types: int, float, double, structs, enums etc.
    • Reference Data Types: string, interface, class, delegates etc.
  • By default, Reference data types are nullable datatypes i.e. we can assign null value to these datatypes.
  • Let's say, if I want to initialize a string with null value, I need to use this code: string[ ] data = null;
  • On the contrary, Value Data Types are non nullable by default in C# i.e. we can't initialize an integer with null value.
  • But we can make a value data type nullable by using a ( ? ) sign in front of the datatype.
  • int? i = null; It will work fine and won't create any error because now i has created a nullable integer.
Why we need nullable ?
  • Let's say you are designing a sign up form and you want user to select the gender i.e. male or female.
  • We can store this value in Boolean variable but what happens if the user doesn't select any value.
  • That's where nullable comes in handy and in this third case where user hasn't selected any value, we can assign a null value to our Boolean variable.
That's all for today. I hope you have got a clear idea about data types in C# language. However, if still you feel skeptical or have any question, you can ask me in the comment section below. I'll try to resolve your query according to best of my expertise. Keep your feedback and suggestions coming, it will help us to augment the quality of our article and give you flawless work that resonates with your needs and expectations. Stay tuned!
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir