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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...