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.

  1. public class Person  
  2. {  
  3. }  

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.

  1. 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.

  1. Person mahesh = new Person();  
  2. Person you = new Person();  
  3. 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.

  1. class Person  
  2. {  
  3.     // private fields  
  4.     private string name;  
  5.     private string sex;  
  6.     private bool student = false;  
  7.   
  8.     // Public properties  
  9.     public string Name { get => name; set => name = value; }  
  10.     public string Sex { get => sex; set => sex = value; }  
  11.     public bool Student { get => student; set => student = value; }  
  12. }  

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.

  1. // Create an object  
  2. Person p = new Person();  
  3.          
  4. // Set Person properties  
  5. p.Name = "Mahesh Chand";  
  6. p.Sex = "Male";  
  7. 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.

  1. // Get properties values  
  2. string personName = p.Name;  
  3. string personSex = p.Sex;  
  4. 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.

  1. // Public methods  
  2. public string Sleep()  
  3. {  
  4.     return "Person is sleeping";  
  5. }  

The following code snippet calls the method, Sleep.

  1. 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.

  1. class Person  
  2. {  
  3.     // private fields  
  4.     private string name;  
  5.     private string sex;  
  6.     private bool student = false;  
  7.   
  8.     // Public properties  
  9.     public string Name { get => name; set => name = value; }  
  10.     public string Sex { get => sex; set => sex = value; }  
  11.     public bool Student { get => student; set => student = value; }  
  12.   
  13. // Public methods  
  14.         public string Sleep()  
  15.         {  
  16.             return "Person is sleeping";  
  17.         }  
  18.   
  19.         // Two int type Parameters method   
  20.         public int add(int a, int b)     
  21.         {  
  22.             return a + b;  
  23.         }  
  24.         // Three int type Parameters with same method same as above    
  25.         public int add(int a, int b, int c)    
  26.         {  
  27.             return a + b + c;  
  28.         }  
  29.         // Different input parameters   
  30.         public double add(int a, double b, long c)  
  31.         {   
  32.             return a + b + c;  
  33.         }  
  34.     }     
  35. }  

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

  1. Person p = new Person();  
  2. int num1 = p.add(5, 10);  
  3. 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().

  1. public class Author : Person  
  2. {  
  3.     private string genre = "Fiction";  
  4.   
  5.     public string Genre { get => genre; set => genre = value; }  
  6.   
  7.     public string Write()  
  8.     {  
  9.         return "I write";  
  10.     }  
  11. }  

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.

  1. // Create an object  
  2. Author author = new Author();  
  3.   
  4. // Set Person properties  
  5. author.Name = "Mahesh Chand";  
  6. author.Sex = "Male";  
  7. author.Student = true;  
  8.   
  9. // Show a message  
  10. 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

  1. interface IParentInterface    
  2. {    
  3.     void ParentInterfaceMethod();    
  4. }    
  5.     
  6. interface IMyInterface : IParentInterface    
  7. {    
  8.     void MethodToImplement();    
  9. }    
  10.     
  11. class InterfaceImplementer : IMyInterface    
  12. {    
  13.     static void Main()    
  14.     {    
  15.         InterfaceImplementer iImp = new InterfaceImplementer();    
  16.         iImp.MethodToImplement();    
  17.         iImp.ParentInterfaceMethod();    
  18.     }    
  19.     
  20.     public void MethodToImplement()    
  21.     {    
  22.         Console.WriteLine("MethodToImplement() called.");    
  23.     }    
  24.      
  25.     public void ParentInterfaceMethod()    
  26.     {    
  27.         Console.WriteLine("ParentInterfaceMethod() called.");    
  28.     }    
  29. }    

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.

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

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

  1. if (author.Student)  
  2. {  
  3.     Console.WriteLine("Author is a student");  
  4. }  
  5. else  
  6. {  
  7.     Console.WriteLine("Author is not a student");  
  8. }  

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

  1. if (author.Student)  
  2. {  
  3.     Console.WriteLine("Author is a student");  
  4. }  
  5. else if (author.Sex == "Male")  
  6. {  
  7.     Console.WriteLine("Author is not a male student");  
  8. }  

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.

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

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

  1. int counter = 0;  
  2. do  
  3. {  
  4.     Console.WriteLine(counter);  
  5.     counter++;  
  6. 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.

  1. int counter = 0;  
  2. while (counter < 10)  
  3. {  
  4.     Console.WriteLine(counter);  
  5.     counter++;  
  6. }  

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.

  1. int[] odds = new int[] { 1, 3, 5, 7, 9, 11 };  
  2. int count = 0;  
  3. foreach (int num in odds)  
  4. {  
  5.     count++;  
  6.     Console.WriteLine(num);  
  7. }  

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.

  1. int caseSwitch = 3;  
  2.   
  3. switch (caseSwitch)  
  4. {  
  5.     case 1:  
  6.         Console.WriteLine("Case 1");  
  7.         break;  
  8.     case 2:  
  9.         Console.WriteLine("Case 2");  
  10.         break;  
  11.     case 3:  
  12.         Console.WriteLine("Case 3");  
  13.         break;  
  14.     default:  
  15.         Console.WriteLine("Default case");  
  16.         break;  
  17. }  

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