8.1. Introduction To Classes: Class Classname (//code Here)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

8.1.

Introduction to Classes

We know Class describes the state & behaviour of objects. Thus a Class decides/ defines what an object does and  what data it holds.

After creating/ designing a Class, any number of similar objects can be created.

Thus, a class becomes the template for an object .An object becomes the instance of its class.

How to write a C# Class

The syntax of the class is as follows:

class   ClassName

//code here

For e.g.; Suppose we have to create a class for Customer, then

Class Customer

    //code here;

Classes – Properties, Get & Set

The variables declared inside a Class are by default not accessible from other Classes, but to access the values from outside,properties

are used.

The properties are special methods called as Accessors, which allows the data to be assigned to/ accessed from the variable, through

Read-only/ Write-only/ Read-Write permissions. The properties enable a class to expose only the getting & setting of values, while

hiding the implementation of code.

The syntax of the property is as follows:

Accessmodifier datatype PropertyName

get { return variablename; }


set { variablename= value; }

        The property contains 2 blocks, a get block, which is called Get accessor & set block, which is called Set accessor. When the data

has to be read using the property, the get accessor will work & when the data has to be assigned to, the set accessor will work.

       Thus the property restricts the access to the value. Property containing only the get block/ get accessor is a Read-Only Property. A

property containing only the set block/ set accessor is the Write-Only property, the Property containing both the Get & Set Accessor is a

Read-Write Property.

For e.g.; we will include the properties for Id & name in our customer class. The Id of the customer is restricted from modification

whereas the name can be given with Read-Write Permission. Our Class will look like as follows:

class Customer

    {

      //Declaration of Variable

        private int _id=0 ;

      //Property for ID restricted from assigning new values

        public int ID

        {

            get { return _id; }

        }

     //Declare Variable for name & use Property for Read & Write

        private string _name;

        public string Name

        {

           get { return _name; }

            set { _name = value; }

        }

8.2. Classes - Constructors


Constructors help to pass the initial values to the variables declared in a class, during the creation of its object.

In C#, the variables inside a class are initialized with default values using a constructor. A constructor should have the same name as

that of the class. The initial values are passed as parameters.

The Syntax of a Constructor is as follows:

  AccessModifier ClassName(datatype parameter1,datatype parameter2)

   {

       variable1 =parameter1;

       variable2 = parameter2;

    }

Since the constructor needs to be accessed from other Classes, the Access modifier will always be public (most permissive).

For e.g.; we can include a Constructor also in our class Customer, for initializing the Id and name of any customer. Now, our class will

look like:

class Customer

    {

        //Declaration of Variable

        private int _id = 0;

        //Property for ID restricted from assigning new values

        public int ID

        {

            get { return _id; }

        }

        //Declare Variable for name & use Property for Read & Write

        private string _name;

        public string Name

        {

            get { return _name; }

            set { _name = value; }

        }

        //Constructor for passing the initial value(as parameter) to the variables

        public Customer(int id, string name)


        {

            //variable = parameter

            _id = id;

            _name = name;

        }

    }

A class can have multiple constructors. Also, if a class does not contain a constructor, C# will instantiate the default values using a

default Constructor.

Encapsulation - OOPS Concept

C# support object- Oriented Programming Approach, which include : Encapsulation, inheritance & Polymorphism.

Encapsulation: A group of related members treated as a single unit. A Class is a single unit which keeps the variables, its related

properties, constructors & other members inside it. Here the members are encapsulated within the Class.

For e.g; our  customer class holds some members. Using Encapsulation, all the members are treated as a single unit using the class

name Customer.

8.3. Object Creation and Initialization

A class defines the type of object. So the object will have the type as the Class name. And the object is created using the “new”

keyword followed by the constructor. The constructor is invoked by the new operator.

The syntax of creating an object using a default constructor for a Class with name ClassName, is as follows:

ClassName objectName= new ClassName();   

Here, ClassName() - is used to invoke the default constructor.

The syntax of creating an object with parameterized constructor is as follows:

ClassName objectName = new ClassName(newValue);

Here, ClassName(newValue) – is used to invoke the parameterized Constructor taking only one value as the parameter and newValue

represent the value to the variable initialised inside the Constructor.

For e.g.; we will see how to create an object of our class customer, using a default Constructor:

            Customer customer= new Customer();


Now, we will see how to create an object of our class customer using parametrized Constructor:

            

            Customer newCustomer = new Customer(100, “Jack”);

Classes - Main Method

 In C#, Console Application or a Windows Application needs to have starting point for the program. The Main Method is defined as the

entry point of a “.exe” program, i.e. the program starts execution from the Main Method.

       One class should contain a Main Method. Since the execution starts from the Main Method and it is invoked without creating an

object of the Class, the Main method should be defined using the "static" keyword.

        Main method should also specify a return type. The return type can be either "void" type which means returns nothing or “int”

datatype which means returns an integer value by the completion of Main method.

       Main Method can be defined with or without parameters. The Parameter are used to take the Command line Arguments and the

parameters are defined using string[] args.

The syntax of the Main Method can be given as follows:

                  static void Main()

                     {

                            //code here

                     }

or

                    static void Main(string[] args)

                     {

                              //code here

                     }

Here we will see the Class program with the Main Method creating the objects of class customer and using the members defined inside.

 class Program

    {

        static void Main(string[] args)

        {

            Customer customer = new Customer();

           customer.Name="Joe";

            Console.WriteLine("{0} :: {1}", customer.ID, customer.Name);


            Customer newCustomer = new Customer(100, "Jack");

            Console.WriteLine("{0} :: {1}", newCustomer.ID, newCustomer.Name);

            Console.ReadKey();

        }

    }

class Customer

    {

        //Declaration of Variable

        private int _id = 0;

        //Property for ID restricted from assigning new values

        public int ID

        {

            get { return _id; }

        }

        //Declare Variable for name & use Property for Read & Write

        private string _name = string.Empty;

        public string Name

        {

            get { return _name; }

            set { _name = value; }

        }

        //Constructor for passing the initial value(as parameter) to the variables

        public Customer(int id, string name)

        {

            //variable = parameter

            _id = id;

            _name = name;

        }

        //Constructor with 0 arguments

        public Customer()

        {
            //

        }      

    }

Output:

0 :: Joe

100 :: Jack

8.4. C# Code and Naming Conventions

1. Class Naming Convention - Class names should be nouns, in Pascal casing.

For e.g; class Customer, class CustomerManager.

2. Variable Naming Convention - Variable names can be short, but need to be meaningful for the purpose. All variable names can

start with a lower case first letter and the next word in the same start with capital letter. Variable name should be mnemonic — that is,

designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided.

3. Property Naming Convention – Property names are given Similar as that of corresponding member, in pascal casing.

    For e.g; Id, Name, BasicPay, RegistrationStatus.

4. Comments – In C#, single line Comments are given using // & multi-Line comments are given using /* and */.

8.5. Practice Problems

Write a class with a main method that will print you the Name, Designation, and Place on the console.

output should be

Name: Jacquil

Designation: Consultant

Place: LA

9O9 is a web shoppe which helps the user to purchase their item in a convenient manner. But to order the items the user need to

register first and then generate an online Bill after the internet banking.
In this scenario, you might have identified some objects, what are they? What is the name of the Class chosen for the Registration

details of the User?

The objects that we can find here are User, Item, Bill. We need an object for the user for the registration details.

To create an object for the user, we need a class with name User. We need variables for taking the user details like First Name, Last

Name, age and Location and Email ID. We will be passing the values to the user object during the time of object creation, so we need a

Constructor. Then we need to provide Properties for the variables.

To start with the execution and work with the User class, we will include a Program class with Main method.

Test the User registration by using 3 user objects. Print the name of the user using the objects created.

Output Should be:

Give the details of users like Haris Jack . Print the Last name, First name of the user as output. I.e;

Jack, Haris

Solutions:

class User

//Variables

private string _firstname = string.Empty;

private string _lastname = string.Empty;

private int _age =0;

private string _location = string.Empty;

private string _email = string.Empty;

//Constructors

public User()

//

public User(string firstname, string lastname, int age,string location, string email)
{

_firstname = firstname;

_lastname = lastname;

_age = age;

_location = location;

_email = email;

//Properties

public string FirstName

get

return _firstname;

set

_firstname = value;

public string LastName

get

return _lastname;

set
{

_lastname = value;

public int Age

get

return _age;

set

_age = value;

public string Location

get

return _location;

set

_location = value;

}
public string EmailId

get

return _email;

set

_email = value;

class Program

static void Main(string[] args)

//Assign values using constructors.

User user1 = new User("Haris","Jack", 40, "LA", "[email protected]");

Console.Write(user1.LastName);

Console.Write(", ");

Console.WriteLine(user1.FirstName);

User user2 = new User();

//Assign values using properties.

user2.FirstName = "Robert";

user2.LastName = "George";

user2.Age = 60;
user2.Location = "LA";

user2.EmailId = "[email protected]";

Console.Write(user2.LastName);

Console.Write(", ");

Console.WriteLine(user2.FirstName);

//Assign values using constructors by getting input from user.

Console.WriteLine("Enter first name,last name,age,location and email");

string firstname = Console.ReadLine();

string lastname = Console.ReadLine();

int age = Convert.ToInt32(Console.ReadLine());

string location = Console.ReadLine();

string email = Console.ReadLine();

User user3 = new User(firstname,lastname,age,location,email);

Console.Write(user1.LastName);

Console.Write(", ");

Console.WriteLine(user1.FirstName);

Console.ReadKey();

Output:

Jack, Haris

George, Robert

Enter first name,last name,age,location and email

Joe

Wilson

50
London

[email protected]

Wilson,Joe

This solution shows 3 types of object creation and data initialization.

You might also like