Basics Of C#

This article explains basics of C#. C# is an object-oriented programming language. The foundation of an object-oriented programming is a type system universe. In the type system universe, everything revolves around classes and objects.

C# Class and object

In C#, a class is a representation of a type of object. It is a blueprint / plan / template that describes the details of an object. In simple terms, a class is a concept and an object is real entity with value.

For example, a Person is a class. A person has some attributes such as a person has a name, a date of birth, and sex. All real people are objects that are of a Person type. Each person object has a name, a date of birth, and sex but the values of these attributes may be different. The attributes of a class are called properties.

Not only a person has attributes, a person can also do something. For example, a person can eat, sleep, talk, or walk. The activities of classes are represented in form of events and methods.

Declaring a class

The following code example shows how to create a class and objects.

A class always starts with the keyword class followed by a class accessibility level, public or private. The following code snippet declares a public class named Person. That means, the class is public and accessible anywhere in the code.

public class Person
{
}

A class has an access modifier. The access modifiers sets the boundaries and access levels of classes. C# supports public, private, protected, internal, and protected internal access modifiers. Learn more about access modifiers here. C# Access Modifiers with Examples.

Creating objects

Objects in C# are created using the new keyword. The following code snippet creates an object of class Person.

Person p = new Person();

Object p in the above code is also called an instance of Person class.

You can create as many objects required from a class. The following code snippet creates three instances of Person.

Person mahesh = new Person();
Person you = new Person();
Person me = new Person();

Each instance in the above code reserves its own memory allocation in a computer memory.

Learn more about objects and classes in C# here. Object-Oriented Programming Using C#.NET.

Types of classes

C# language has different types of classes, such as static classes, abstract classes, partial classes, and sealed classes. Learn more about classes here. Types of Classes In C#.

Class Members

A class consists of members such as fields, variables, properties, events, enumerations, stucts, and methods. Each member of the class has a specific purpose.

Properties

A property in C# is a member of a class that provides a flexible mechanism for classes to expose private fields. Internally, properties are special methods called accessors. A property have two accessors, get property accessor and set property accessor. A get accessor returns a property value, and a set accessor assigns a new value. The value keyword represents the value of a property.

Properties in C# and .NET have various access levels that is defined by an access modifier. Properties can be read-write, read-only, or write-only. The read-write property implements both, a get and a set accessor. A write-only property implements a set accessor, but no get accessor. A read-only property implements a get accessor, but no set accessor.

The following code snippet adds three properties, name, sex, and student to the Person class. As you can see from the code, all three properties provide access to three fields of the class.

class Person
{
    // Private fields
    private string name;
    private string sex;
    private bool student = false;

    // Public properties
    public string Name
    {
        get => name;
        set => name = value;
    }

    public string Sex
    {
        get => sex;
        set => sex = value;
    }

    public bool Student
    {
        get => student;
        set => student = value;
    }
}

To set public properties of a class, you need the setter of a property to set the value. The following code snippet sets the values of properties of a Person.

// Create an object
Person p = new Person();

// Set Person properties
p.Name = "Mahesh Chand";
p.Sex = "Male";
p.Student = true;

To access a class properties, you use the getter of the property. The following code snippet gets the values of properties of a Person.

// Get properties values
string personName = p.Name;
string personSex = p.Sex;
bool isPersonStudent = p.Student;

Learn more about properties, read Understanding Properties in C#.

Methods

Classes in C# has a purpose. Not only classes represent data, but classes can also do process something. The processing is usually is the execution of the code to achieve some task. The processing in a class is done via events and methods.

A method usually a code snippet that does a specific task. For example, you may have a class name Calculator with methods, Add and Subtract. The Add method takes two numbers and returns the total of the two. The Subtract method takes two numbers and subtracts the second number from the first and returns the result.

The following code snippet declares a method, Sleep in Person class. The method returns a string.

// Public methods
public string Sleep()
{
    return "Person is sleeping";
}

The following code snippet calls the method, Sleep.

Console.WriteLine(p.Sleep());

If you want to learn more about methods and object-oriented programming, here is a free eBook download.

What is Polymorphism?

Polymorphism is one of the core properties of an object-oriented programming. It allows a language method to do various things using the same name. Method overloading, operator overloading, and method overriding are the examples of polymorphism. C# language supports both method overloading and method overriding.

Method Overloading

Method overloading allows class creators to use same method name with different signatures. This is useful to write clean code. For example, if you have a Calculator class that has a method, Add. The Add method can add integers, floats, doubles, and longs. We can use the same Add method name with different argument types in method signatures.

Let’s look at the following code snippet. In the Person class, we’ve a method, Add with three different signatures. The method will be executed based on the arguments passed by the caller class.

class Person
{
    // Private fields
    private string name;
    private string sex;
    private bool student = false;

    // Public properties
    public string Name
    {
        get => name;
        set => name = value;
    }

    public string Sex
    {
        get => sex;
        set => sex = value;
    }

    public bool Student
    {
        get => student;
        set => student = value;
    }

    // Public methods
    public string Sleep()
    {
        return "Person is sleeping";
    }

    // Two int type Parameters method
    public int Add(int a, int b)
    {
        return a + b;
    }

    // Three int type Parameters with same method name as above
    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }

    // Different input parameters
    public double Add(int a, double b, long c)
    {
        return a + b + c;
    }
}

The following code class the Add method twice with different signatures and both time, different code is executed in the Person class.

Person p = new Person();
int num1 = p.Add(5, 10);
int num2 = p.Add(2, 4, 6);

Method Overriding

Method overriding is a language feature that allows a class to override a specific implementation of a a base class. The derived class can give its own definition and functionality to the method. However, the method signature must be the same as of the base class.

Here is an article on method overriding.

Inheritance

C# is an object-oriented programming language. Inheritance is one of the key features of an object-oriented programming language.

Inheritance allows a class to be reused by other classes that may need the same functionality. Inheritance works as a parent and child, where the parent is called a base class and the child is called a derived class. A derived class inherits almost all of the functionality of a base class unless it is restricted by private access modifier.

Let’s see, we derive a class, Author from class Person. As you can see from the following code example, the Author class has one property, Genre, and one method, Write().

public class Author : Person
{
    private string genre = "Fiction";

    public string Genre
    {
        get => genre;
        set => genre = value;
    }

    public string Write()
    {
        return "I write";
    }
}

Now, when we create an Author class instance, we can actually access the Person (the base class) class’s members. The following code creates an instance of the Author class and sets its Name, Sex, Student properties, that are declared in the Person class.

// Create an object
Author author = new Author();

// Set Person properties
author.Name = "Mahesh Chand";
author.Sex = "Male";
author.Student = true;

// Show a message
Console.WriteLine($"Person {author.Name} writes {author.Genre} books.");

Here is a more detailed article on Inheritance.

What is Abstraction?

Sometimes there is a class which does not create objects; this class provides a definition to other derived classes. This class is known as an abstract class and the method is known as an abstraction.

Basics of C#

Consider the above diagram where Fish is a base class. In class Fish, there is a method, Eat. Fish eat. There are two types of Fish, Dolphin and Sword. The both eat different food but they eat. The abstraction makes sure that both Fish inherited classes implement the Eat method. The inherited

classes now can override the eat() method and provide its own implementation of it.

Interfaces

Interfaces are not often use types in C#. C# language support single interface.

An interface provides a skeleton of a class that must be implemented by the inherited class. It enforces derived classes to implement certain functionality.

In C#, a class is a reference type and an interface is a value type.

C# code

interface IParentInterface
{
    void ParentInterfaceMethod();
}

interface IMyInterface : IParentInterface
{
    void MethodToImplement();
}

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
        iImp.ParentInterfaceMethod();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }

    public void ParentInterfaceMethod()
    {
        Console.WriteLine("ParentInterfaceMethod() called.");
    }
}

Want to learn more about interfaces in C#, here is a detailed article on interfaces in C#. Interfaces Best Examples in C#.

C# Control Statements

C# language supports the following control statements.

  1. The if else statement
  2. The for loop
  3. The foreach loop
  4. The while loop
  5. The do while loop

The if else statement

The if statetement checks for a condition and if the condition is true, code is executed. The following code check if the condition is true.

if (author.Student)
{
    Console.WriteLine("Author is a student");
}

The if else statement checks a condition and executes different code if the condition is true or not.

if (author.Student)
{
    Console.WriteLine("Author is a student");
}
else
{
    Console.WriteLine("Author is not a student");
}

The if else if statement can have several if and else statement.

if (author.Student)  
{  
    Console.WriteLine("Author is a student");  
}  
else if (author.Sex == "Male")  
{  
    Console.WriteLine("Author is not a male student");  
}  

The For loop

The for statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. The following code snippet uses a for loop to execute code until the counter is < 10.

for (int counter = 0; counter < 10; counter++)
{
    Console.WriteLine(counter);
}

The do loop

The do statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. Because that expression is evaluated after each execution of the loop, a do-while loop executes one or more times. This differs from the while loop, which executes zero or more times.

At any point within the do statement block, you can break out of the loop by using the break statement.

Example

int counter = 0;
do
{
    Console.WriteLine(counter);
    counter++;
} while (counter < 10);

The While loop

The while statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. Because that expression is evaluated before each execution of the loop, a while loop executes zero or more times. This differs from the do loop, which executes one or more times. At any point within the while statement block, you can break out of the loop by using the break statement.

int counter = 0;
while (counter < 10)
{
    Console.WriteLine(counter);
    counter++;
}

The foreach loop

A foreach loop operates on collections of items such as an array. The following code snippet loops through an array of numbers and displays array numbers.

int[] odds = new int[] { 1, 3, 5, 7, 9, 11 };
int count = 0;

foreach (int num in odds)
{
    count++;
    Console.WriteLine(num);
}

Switch case

The switch statement is a control statement that handles multiple selections by passing control to one of the case statements within its body.

The following code snippet checks a matching expression and executes the matched case statement.

int caseSwitch = 3;

switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    case 3:
        Console.WriteLine("Case 3");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}

Summary

This article is a basic introduction to C# language. If you want to learn more C#, here is a list of several beginner tutorials.


Similar Articles