ASP.NET: Object Oriented Programing - Introduction to C#

ASP.NET: Object Oriented Programing - Introduction to C#

In this article we will discuss key concepts of object orientation with their practical implementation in C#. We will discuss here basics of OOPS (Object orianted programing) including Interfaces, Access Modifiers, inheritance, polymorphism etc.

Class and Object definition

The basic building blocks of object-oriented programming are the class and the object.

The Key Question of the OOPS it what is object? The simpliest answer to this question is that Object is instance of classes. For people who have never heard about classes they can be now really confused? What is a class?

Classes are blueprints for Object. The terms class and object are sometimes used interchangeably, but in fact, classes describe the type of objects, while objects are usable instances of classes. So, the act of creating an object is called instantiation. Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint.

Object can be representation of something from the real world. For example if we want to show some basic information about user who is logged in on our website, we need to create a new class User. We need to think about things that are in common for all users, for example it could be age, first name, last name and user password. For start this is enough information. Now we will create our first class in C#.

C# Example of Class User:
public class User
{

}

We can learn a lot from this example. For a class definition we use a two keywords a keyword class and keyword public (we will discuss later about keywords in C#). Keyword class uses for the class definition and keyword public is access modifer.

What are Access Modifiers in C#

Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

Public is visible to everyone. A public member can be accessed using an instance of a class, by a class's internal code, and by any descendants of a class.

Private is hidden and usable only by the class itself. No code using a class instance can access a private member directly and neither can a descendant class.

Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.

Internal/Friend is public to the entire application but private to any outside applications. Internal is useful when you want to allow a class to be used by other applications but reserve special functionality for the application that contains the class. Internal is used by C# and Friend by VB .NET.

Protected Internal may be accessed only by a descendant class that's contained in the same application as its base class. You use protected internal in situations where you want to deny access to parts of a class functionality to any descendant classes found in other applications.

Instantiating an Object from a C# Class

When we work with an object we are using a reference to that object. On the other hand, when we are working with simple data types such as Integer, we are working with the actual value rather than a reference.

When we create a new object using the new keyword, we store a reference to that object in a variable. For instance:

User userInfo = new User();

This code creates a new instance of User. We gain access to this new object via the userInfo variable. This variable holds a reference to the object. Now when we have created object we can acces its class members. For now our class doesn't have any members. So in the next step we will discuss how to create class members.

Creating C# Class Members

Class members or properties are essentially variables and methods embedded into the class. Members can be public, private or protected (see section access modifers).

This is the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters). We will talk about this later when we start working with the properties in C#.

We can now extend our User class to add member variables to hold the user first name, last name, email and age. True to the concept of data encapsulation we will be making some of these members private and writing methods to access these values later:

public class User
        {
            public string firstName;
            public string lastName;
            public string email;
            public int age;
            private string password;
        }

Now that we have defined the properties of our class we need to look briefly at a few additional data member types, and then learn how to create object instances from the class.

Accessing C# Object Members

Now that we know how to write a class and instantiate objects from the class, we now need to know how to access the members of the object. Firstly, you will recall that we declared some members as being public and others as being private. The public methods are fully accessible from outside the object. This is achieved using something called dot notation. Dot notation is a mechanism by which object members may be accessed by specifying the object and member names separated by a dot (.). For example, to access the firstName member of an object named userInfo we would reference this member using userInfo.firstName:

using System;

namespace JohnnyMarshal.Tutorial
{
    class FirstProgram
    {
        public class User
        {
            public string firstName;
            public string lastName;
            public string email;
            public int age;
            private string password;
        }

        static void Main(string[] args)
        {
            User userInfo = new User();

            userInfo.firstName = "John";
            userInfo.lastName = "Johnson";
            userInfo.age = 25;

            Console.WriteLine("You are logged in as " + userInfo.firstName + " " + userInfo.lastName);
        }
    }
}

The above code assigns values to the firstName, lastName and age members of our object. It then references the properties in order to display text which reads:

You are logged in as John Johnson

This approach works well for public class members, but not for private members. An attempt, for example, to use dot notation to access the private accountNumber member will result in a compilation error along the the lines of:

Error 3 'JohnnyMarshal.Tutorial.FirstProgram.User.password' is inaccessible due to its protection level

In order to access private members we need to provide access methods in the class.

Methods

Class method members are sections of code contained in a class which can be called from outside an object to perform specific tasks. Common types of methods are getter and setter methods which are used to access private data members of a class. For example, we can declare a getter and a setter method to get and set the protected password member:

public class User
        {
            public string firstName;
            public string lastName;
            public string email;
            public int age;
            private string password;

            public void SetPassword(string newPassword)
            {
                password = newPassword;
            }

            public string GetPassword()
            {
                return password;
            }
        }

Class methods are called using dot notation. For example, to set the value of the password:

User userInfo = new User();
            userInfo.SetPassword("password");
            Console.WriteLine("User passowrd is " + userInfo.GetPassword());

The above code sets the password using the setter method and then displays the password using the getter method. Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, then the method can return the value using the return keyword. Methods with a non-void return type are required to use the return keyword to return a value.
Now that we have looked at method class members the next task is to look at two special class methods, constructors and finalizers.

C# Constructors and Finalizers

Despite the grand sounding names, C# class constructors and finalizers are nothing more than methods which get called when an object is instantiated and destroyed. The constructor is particularly useful for allowing initialization values to be passed through to an object at creation time. Let's say that we would like to be able to initialize the firstName and alastName members at the point that we initialize the userInfo object. To do so we need to declare a constructor.

Constructors are declared the same way as other methods with the exception that the name of the method must match the class name:

public class User
{
 public User(string fName, string lName)
 {
  firstName = fName;
  lastName = lName;
 }

 public string firstName;
 public string lastName;
 public string email;
 public int age;
 private string password;

 public void SetPassword(string newPassword)
 {
  password = newPassword;
 }

 public string GetPassword()
 {
  return password;
 }
}

We can now use the constructor to initialize these members at object creation:

User userInfo = new User("John", "Johnson");

Finalizers are used to clean up any resources used by a class object when the object is destroyed. Unlike constructors which can be triggered from code using the new keyword there is no way to explicitly call a finalizer (for example there is no delete equivalent to the new keyword). Instead, the finalizer will be called when the garbage collector decides that the object instance is no longer needed. All the programmer can be sure of is that the finalizer will be called at some time between the when the object is no longer needed by the code and the point that the application terminates.

Posted by Ingenium Web

Ingenium Web

iNGENIUM Ltd. is an software development company from EU which delivers a full range of custom .NET, web and mobile solutions for different business to meet partner's demand.

The Power of Imagination Makes Us Infinite

Related Posts

Comments

comments powered by Disqus