You are on page 1of 7

Lab 04

Introduction to Classes and Objects (C#)

Objectives
● To learn about the C# Programming Language and general syntax along with Classes and
Objects.

Namespaces
To make the ​.NET Framework​ more manageable, Microsoft has given it a hierarchical structure. This
hierarchical structure is organized into what are referred to as ​namespaces​. By organizing the
framework into namespaces, the chances of ​naming collisions​ are greatly reduced. Organizing related
functionality of the framework into namespaces also greatly enhances its usability for developers. For
example, if you want to build a window’s GUI, it is a pretty good bet the functionality you need exists in
the:
"System.Windows"​ namespace.

Class
A ​class ​is considered as a construct which encapsulates a group of variables and methods​.
(Definition from book) In OOP, class is called a definition (specification) of a given type of objects from
the real-world. The class represents a pattern, which describes the different states and behavior of
certain objects (the copies), which are created from this class (pattern).

Object
In OOP terms, an ​object ​is an instance of class for incorporating data and the procedures for working
with that data.
(Definition from book) An ​object​ is a copy created from the definition (specification) of a given class, also
called an instance. When one object is created by the description of one class we say the object is from
type "name of the class".

The general structure of a class declaration is as follows:


class ClassName {

// functions
public void functionName {
// function body
}

// member variables
private string message;
}

Example 4.1

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello C#!");
System.Console.ReadLine();
}
}
}

Output
Hello C#!

Note: Here we introduce System.Console.ReadLine() so that terminal after displaying output does not
get close. We will see other ways of compiling also.

Data Types and Functions


We will see that the majority of the data types which we used earlier in C++, remains similar in C# too.
Also, using the function

Example 4.2 - Data Types and Functions

static void Main(string[] args){


Program program = new Program();

int num1 = 23, num2 = 33;


char a = 'a', e = 'e', i = 'i', o = 'o', u = 'u';
float pie = 3.148f;
int radius = 5;
System.Console.WriteLine("Sum of two numbers is: "
+ program.sum(num1, num2));
System.Console.WriteLine("Area of Circle is: "
+ program.calculateAreaOfCircle(pie, radius));

char userOption;

System.Console
.WriteLine("Input character to check if it is a vowel or not: ");

userOption = System.Console.ReadLine()[0];

System.Console.WriteLine("Input Character is vowel: "


+ program.isVowel(userOption, a, e, i, o, u));
System.Console.ReadKey();
}

private int sum(int num1, int num2) {


return num1 + num2;
}

private float calculateAreaOfCircle(float pie, int radius) {


return pie * radius * radius;
}

private bool isVowel(char userOption, char a,


char e, char i, char o, char u) {

return userOption == a || userOption == e


|| userOption == i || userOption == o || userOption == u;
}

Output
Sum of two numbers is: 56
Area of Circle is: 78.7
Input character to check if it is a vowel or not:
a
Input Character is vowel: True

Lab Task 01:


Create functions for addition, subtraction, multiplication, and division to perform each operation on
given 2 numbers.

string
A ​string ​is a sequence of characters stored in a certain address in memory. In the variable of type ​char
we can record only one character. Where it is necessary to process more than one character then strings
come to our aid.
The ​System.String​ Class

The class ​System.String e​ nables us to handle strings in C#. For declaring the strings we will continue
using the keyword string, which is an alias in C# of the System.String class from .NET Framework. The
work with string facilitates us in manipulating the the text content: construction of texts, text search and
many other operations.

Example of declaring a string


string greeting = "Hello, C#";

We have just declared the variable greeting of type string whose content is the text phrase "Hello, C#".
The representation of the content in the string looks closely to this:

H e l l o , C #

Question:
What is the use of string class when we can use char array?

Example 4.3 - String manipulation

static void Main(string[] args) {

string message = "This is a sample string message.";

System.Console.WriteLine("message = {0}", message);


System.Console.WriteLine("message.Length = {0}", message.Length);

for (int i = 0; i < message.Length; i++)


{
System.Console.WriteLine("message[{0}] = {1}", i, message[i]);
}

System.Console.WriteLine();
System.Console.WriteLine();

string quote = "Book's title is \"Intro to C#\"";

System.Console.WriteLine(quote);

System.Console.WriteLine();
System.Console.WriteLine();

System.Console.WriteLine("Enter any string: ");


string str = Console.ReadLine();

System.Console.WriteLine("You entered: {0}", str);


System.Console.ReadKey();
}

Output
message = This is a sample string message.
message.Length = 31
message[0] = T
message[1] = h
message[2] = i
message[3] = s
....
Book's title is "Intro to C#"
Enter any string:
DHA Suffa University
You entered: DHA Suffa University

Lab Task 02:


Given a character ch and string str, count the number of times ch is repeated in a str.
ch = ‘o’, str = “hello world”. Take input from user.
Output = 2

More on ​string

word1.Equals(word2) To compare the two strings in order to determine whether their


values are equal or not

word1 == word2 Compares the address (objects)

word1.CompareTo(word2) If you want to compare two words and get information which one
of them is before the other according to their alphabetical order
of letters

string.Concat(greet, Concatenate two strings and return the result


name);

str.ToLower() Changes all characters to lowercase

str.ToUpper() Changes all characters to uppercase

str1.IndexOf(str2); Returns the starting index of str2 in str1 if present, else returns
-1
str.Substring(startIndex, Returns substring of str from start index to start index + number
numberOfChars); of characters specified

str.Split(separators,StringS Breaks the string on basis of separators.


plitOptions.RemoveEmpty *separators = char [ ]
Entries);

Lab Task 03:


Given two strings, find if they are anagrams or not.
Eg., str1 = race and str2 = care.
The strings are anagram because both uses equal count of characters.

Home Assignment

Task 01:
Find if given string is a palindrome or not.
Str = level
Output = Palindrome

Task 02:
Print duplicate characters from a String.
Str = this is a sample text
Output = isate

Task 03:
Print all substrings of a given String.
Str = suf
Output:
s
su
suf
u
uf
f

Task 04:
Reverse words in a string (It is different from printing string in reverse).
Str = hello world
reverseStr = dlrow olleh

Submission Instructions
1. Number your solution folders as question number e.g. Q1, Q2, etc. (Q is in upper case)
2. Every folder should contain single .cs file
3. Create a new folder named cs152abc where abc is your 3 digit roll #. e.g. cs152111.
4. Copy all the project folders into this folder.
5. Now make sure a zip file named cs152abc.zip is created e.g. cs152111.zip
6. Upload the assignment solution on LMS under the assignment named Lab 04

You might also like