Skip to main content

Object Oriented Programming in C#

Object Oriented Programming in C#

Object oriented programming (OOP) is a programming structure where programs are organized around objects instead of action and logic used in the early age of programming, though some still organize their programs around actions and logic. Understanding OOP concepts can help make decisions about how you should design an application and what language to use.
Everything in OOP is placed together as self-sustainable or self-contained “objects.” An object is a combination of variables, functions, and data that performs a set of related activities. When the object performs those activities, it defines the object’s behavior. In addition, an object is an instance of a class. C# offers full support for OOP including inheritance, encapsulation, abstraction, and polymorphism.
Lets deal with the attributes of OOP one after another.

Inheritance

Inheritance in OPP, is the ability to receive (“inherit”) the behaviours and states of an other existing classes (methods and properties).

For instance, Musa is a son of Suleiman, Musa can inherit the behaviour and characteristics of Suleiman such as looks and feels

Encapsulation

The encapsulation hides the implementation details of a class from other objects, in the another way, encapsulation involves when a group of related methods, properties, and other members are treated as a single object.


Abstraction

The abstraction is the process by which a developer hides everything other than the relevant data about an object in order to simplify and increase efficiency.


Polymorphism

The polymorphism occurs when each class implements the same methods in varying ways, but you can still have several classes that can be utilized interchangeably.

C# Objects

Objects are basic building blocks of a C# OOP program. An object is a combination of data and methods. The data and the methods are called members of an object. Object are created from class, these objects communicate together through methods. Each object can receive messages, send messages and process data.

syntax 

(Blue print)
class sampleClass
{
    
}

syntax

(object)
class Program
    {
        static void Main(string[] args)
        {
            var s = new sampleClass();
            Console.WriteLine(s);
        }
    }


Object Attributes in C#


Object attributes implies the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.



Example of C# object attributes



using System;

namespace CSharpObjectAttributes
{
    class Person
    {
        public string name;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Person();
            p1.name = "Musa";

            var p2 = new Person();
            p2.name = "Sule";

            Console.WriteLine(p1.name);
            Console.WriteLine(p2.name);
        }
    }
}
In the above example, we have one class called Person with one member field 'name'. 
The public keyword used, is to enable us use the field outside the class.

We also create two instances of Person class called p1 and p2 with their member fields set to 
Musa and Sule respectively.

Methods in C#

Methods are functions defined inside the body of a class. They are used to perform operations 
with the attributes of our objects.
Methods are important in the encapsulation concept of the Object Oriented Programming paradigm. For example, we might have a Calculate() method in our GPACalculator class. We need not to be told how exactly the method Calculate() calculates the students' GPA. We only have to know that it is used to calculate student GPA. This is essential in dividing responsibilities in programming, especially in large applications.

Example of C# Method

using System; 
namespace CsharpNaijaMethods 
    class Circle     
    {         
      public int Radius{set;get;}         
      public double Area()
      {             
        return Radius * Radius * Math.PI;           
      }       
    } 
     class Program     
     {       
        static void Main(string[] args)
        {           
           var circle = new Circle();                                     circle.Radius=5;                                               Console.WriteLine(circle.Area());
         }     
     } 
 }
    class Circle   
    {         
      public int Radius{set;get;}         
      public double Area()
      {             
        return Radius * Radius * Math.PI;         
      }     
    } 
     class Program     
     {       
        static void Main(string[] args)
        {           
           var circle = new Circle();                                     circle.Radius=5;                                               Console.WriteLine(circle.Area());
         }     
     } 
From the above example, we created a class called Circle with a property called Radius and one method called Area with a return type of double.
We created on object from the class called circle and initialized the Radius property with value of 5, then Displayed the area of the circle using console.
Methods in C# are a way of influencing object behavior in OOP. That is, object performs certain behavior through methods in the blueprint.

 Access Modifiers in C#

Access modifiers are used to set the visibility of methods and member fields. 
Basic Access Modifiers in C# 
modifiers: publicprotectedprivate and internal. The public members can be accessed from anywhere outside the class. The protected members can be accessed only within the class itself and by inherited and parent classes. The private members are limited to the containing type or class, e.g. only within its class or interface. The internal members may be accessed from within the same assembly (exe or DLL).
There are also two combinations of modifiers: protected internal and private protected. The protected internal type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. The private protected type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
We will see a practical example of access modifiers during project demo.

Constructor in C#

A constructor is a special kind of a method. It is automatically called when an object is created. Constructors do not have return values. The purpose of a constructor is to initiate the state of an object. Constructors have the same name as the class. The constructors are methods, so they can be overloaded too.
Constructors cannot be inherited. They are called in the order of inheritance. If we do not write any constructor for a class, C# provides an implicit default constructor. If we provide any kind of a constructor, then a default is not supplied.
Example of a constructor 
using System;

namespace CsharpnaijaConstructor
{
    class Human
    {
        public Human()
        {
            Console.WriteLine("Human is created");
        }

        public Human(string human)
        {
            Console.WriteLine("Human {0} is created", human);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var h=new Human();
            var h1=new Human("Musa");
        }
    }
}
The new key word in the above example denote creation of an object which
signifies a constructor in c#.

ToString Method in C#

Tostring is a method in C# Class that is automatically inherited from an object class where every class inherit. It returns a huma-readable representation of the object.

Example of ToString method

using System;

namespace CSharpnaijaToStringMethod
{
    class Human
    {
        public override string ToString()
        {
            return "This is Human class";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var h = new Human();
            var o = new Object();

            Console.WriteLine(o.ToString());
            Console.WriteLine(h.ToString());
            Console.WriteLine(h);
        }
    }
}
From the above example, we created a class called Human that override the ToString Method to return the class created. We now created objects from the Human and Object class respectively, we printed the objects on console.


Comments

Post a Comment

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...