You are on page 1of 29

Advanced Programming

Techniques
C# Programming with
Microsoft .NET
Recap…
Demo application….

© Copyright by University of Gujrat


Lecture 3

Understanding C#
Fundamental
Structure of a C# Program?
• Program execution begins from static Main( ).
• using system; using keyword refers to
resources in the .NET Framework class library.
• Statements are commands that perform
actions
– A program is made up of many separate statements
– Statements are separated by a semicolon
– Braces are used to group statements
using
using System;
System;
class
class Salam{
Salam{
static
static void
void Main(string[]
Main(string[] args)
args) {{
Console.WriteLine
Console.WriteLine (“Asalam
(“Asalam Alykum!");
Alykum!");
}}
}}
How to Format Code in C#
• Use indentation to indicate enclosing statements
• C# is case sensitive (cAse and case are 2 diff
things)
• White space is ignored
• Single line comments same as in C or C++ by
using //
• Multiple-line comments by using /* and */
• We can use keyword as an identifier if preceded by
@ e.g. @int;
using
using System;
System;
class
class Salam{
Salam{
static
static void
void Main(string[]
Main(string[] args)
args) {{
Console.WriteLine
Console.WriteLine (“Asalam
(“Asalam Alykum!");
Alykum!");
}}
}}
Programming practices
• By convention, always begin a class name’s identifier with
a capital letter and start each subsequent word in the
identifier with a capital letter. e.g. MyFirstClass
• By convention, a file that contains a single public class
should have a name that is identical to the class name
(plus the .cs extension) in both spelling and capitalization.
• Whenever you type an opening left brace, {, in your
application, immediately type the closing right brace, }
this will help in avoiding braces miss match.
• Ctrl + } helps in identifying pairs
• Properly indented code is always admired, VS IDE also
provide auto indentation. Edit->Advanced->Format
Document.
Predefined Datatypes
• Predefined or primitive datatypes
– Predefined types are those provided by
C# and the .NET Framework
– Most are similar as in C++
– string, decimal, Int32, Int64 etc.
– Decimal datatype special for monetary
values
– Why decimal ? Whats wrong with float n
double?
Formatting Text with Console.Write
and Console.WriteLine
// Displaying multiple lines of text with string formatting.
using System;
public class Welcome4
{
// Main method begins execution of C# application
public static void Main( string[] args )
{
Console.WriteLine( "{0}\n{1}", "Welcome to", "C#
Programming!" );
} // end Main
} // end class Welcome4
Welcome to
C# Programming!
How to Declare and Initialize
Strings
• Example string
string s = "Hello World"; // Hello World

• Declaring literal strings


string s = "\"Hello\""; // "Hello"

• Using escape characters


string s = "Hello\nWorld"; // a new line is added

• Using verbatim strings


string s = @"Hello\n"; // Hello\n

• Understanding Unicode
The character “A” is represented by “U+0041”
// Displaying the sum of two numbers input from the keyboard.
using System;
public class Addition{
// Main method begins execution of C# application
public static void Main( string[] args ) {
int number1; // declare first number to add
int number2; // declare second number to add
int sum; // declare sum of number1 and number2

Console.Write( "Enter first integer: " ); // prompt user


// read first number from user
number1 = Convert.ToInt32( Console.ReadLine() ); // atoi(xyz)
Console.Write( "Enter second integer: " ); // prompt user
// read second number from user
number2 = Convert.ToInt32( Console.ReadLine() );

Enter first integer: 45


sum = number1 + number2; // add numbers Enter second integer:
Console.WriteLine( "Sum is {0}", sum ); // display
72 sum
} // end Main Sum is 117
} // end class Addition
Enumeration Types
• Defining Enumeration Types
enum Planet {
Mercury,
Venus,
Earth,
Mars
}

• Using Enumeration Types


Planet aPlanet = Planet.Mars;

• Displaying the Variables


Console.WriteLine("{0}", aPlanet); //Displays Mars
Classes and Objects
Example statement: “You wants to drive a
car, accelerate it using pedal and apply
breaks to stop it at a particular location.”
Firstly we need a car.
Engineer will design a car and also
design acceleration system and break
system. Break Pedals that hide the
complexity of the break system.
Drivers rarely know the whole working of car.
Classes and objects…

Yet we cant drive until car is build from


the design. Similarly we cant live in a
blueprint of a house.
Classes and objects…
A programming unit that performs a task is
know as Method. Method hides complexity
of implementation similarly Car acceleration
pedal hide the complexity of engine.

Class is a programming unit that contains


methods to perform a particular task
similarly the Engineering Car design contain
the specification of Acceleration pedal.
Classes and objects…
As we cant drive a Engineering Design of car,
similarly we cant benefit from class definition
in our application until we build objects from
it.

Objects interact with each other by passing


messages. (function calls, method invoke).
Classes have properties or attributs similar in
our car example car have property of Color,
Model, Make, No. of speeds.
Classes
// Class declaration with one method. GradeBook
------------
using System;
public class GradeBook
------------
{ + DisplayMessage()

// display a welcome message to the GradeBook user


public void DisplayMessage()
{
Console.WriteLine( "Welcome to the Grade
Book!" );
} // end method DisplayMessage
} // end class GradeBook
Declaring an object of class
and calling function
// Create a GradeBook object and call its DisplayMessage method.
public class GradeBookTest
{
// Main method begins program execution
public static void Main( string[] args )
{
// create a GradeBook object and assign it to myGradeBook
GradeBook myGradeBook = new GradeBook();
myGradeBook.DisplayMessage();
// call myGradeBook's DisplayMessage method
} // end Main
} // end class GradeBookTest

Welcome to the Grade Book!


Class with functions
// Class declaration with one method. GradeBook
------------
using System;
public class GradeBook
------------
{ +
+ DisplayMessage(string
DisplayMessage(string str)
str)

// display a welcome message to the GradeBook


user
public void DisplayMessage(string strCourseName)
{
Console.WriteLine( "Welcome to the {0}!“,
strCourseName );
} // end method DisplayMessage
} // end class GradeBook
Access modifiers private
• private
and public
– Only visible inside a class, not accessible
directly. Information hiding
• public
– Visible to the world, directly accessible.

Now how to access private member?


private string courseName;
We use public functions to modify private members values.
(Security)
e.g. GetCourseName, SetCourseName
Class with variables
// Class declaration with one method. GradeBook
using System; ------------
- nMarks: int

public class GradeBook ------------


+
+ SetMarks(
SetMarks( Marks:
Marks: int)
int)
{ + int GetMarks()
+ int GetMarks()
+
+ DisplayMessage(msg:string)
DisplayMessage(msg:string)

private int nMarks; //member variable


// reading and writhing methods for private variable
public void SetMarks(int val){ nMarks = val; }
public int GetMarks(){ return nMarks; }

public void DisplayMessage(string strCourseName)


{
Console.WriteLine( "Welcome to the {0}!“, strCourseName
);
} // end method DisplayMessage
Variables & Properties
using System;
GradeBook
public class GradeBook ------------
{ -courseName: string
- <<property>>CourseName: string
private string courseName; // course name for this GradeBook
------------
// property to get and set the course name +
+ SetMarks(
+
SetMarks( Marks:
+ int
Marks: int)
int GetMarks()
GetMarks()
int)

+ DisplayMessage(msg:string)
public string CourseName
{
get
{
return courseName;
} // end get
set
{
courseName = value;
} // end set
} // end property CourseName
} // end class GradeBook
Auto implemented
properties
C# provides auto implementation of properties,

public string CourseName { get; set; }


C# compiler creates a private instance variable,
and the get and set accessors for returning and
modifying the private instance variable.

But we cannot take the advantage of checking


values before assigning.
Value Type vs Reference
Types in C# are divided into two categories
—value types and reference types
C#’s simple types are all value types e.g.
int a = 7; // variable a contains values 7

Where as reference type variable contains


address of the memory location. e.g.
GradeBook myGradBook;
Default value = null;
Constructors
Constructor is a function which is automatically called when an
object is created
•Class provides a constructor that can be used to initialize an
object of a class when the object is created.
Name is similar as class
using System;
public class GradeBook
{
public GradeBook()
{}
} // end class GradeBook No return type Why?

GradeBook gradeBook =new GradeBook();


Default Constructors
using System;
public class GradeBook
{
public string CourseName { get; set; }
public GradeBook()
{
CourseName = “Unknown”;
}
….
} // end class GradeBook

GradeBook gradeBook =new GradeBook();


Constructors with
using System;
arguments
public class GradeBook
{
public string CourseName { get; set; }
public GradeBook(string courseName)
{
CourseName = coursename;
}
} // end class GradeBook

GradeBook gradeBook =new GradeBook(“Visual Programming”);


“Also Known as constructor overloading”
Overloaded Constructors
public class GradeBook

{
public string CourseName { get; set; }
public GradeBook(string courseName)
{
CourseName = coursename;
GradeBook();
}
public GradeBook()
{ Console.WriteLine(“I am a default
constructor”);}

} // end class GradeBook


Why we need
constructors?
Some times we must initialize class variables to
avoid undesirable results.
public class Counter
{
public string CurrentCount{ get; set; }
public Counter()
{
CurrentCount = 0;
}
public void Increment() { CorrentCount++;}
} // end class Counter

Counter counter1=new Counter();


Thank you!

You might also like