0% found this document useful (0 votes)
125 views

CChapter 3 - C-Sharp Language Funcamentals

The document discusses the basics of C# programs and code structure. It covers creating a simple "Hello World" program with the Main method, using classes, objects, constructors, and member variables. It also discusses input/output using the Console class, default variable values, and formatting output. Examples are provided to demonstrate these core C# language concepts.

Uploaded by

Rudresh CM
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views

CChapter 3 - C-Sharp Language Funcamentals

The document discusses the basics of C# programs and code structure. It covers creating a simple "Hello World" program with the Main method, using classes, objects, constructors, and member variables. It also discusses input/output using the Console class, default variable values, and formatting output. Examples are provided to demonstrate these core C# language concepts.

Uploaded by

Rudresh CM
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

C# Language Fundamentals

GRNICA 2
The Anatomy of a Simple C# Program
// By convention, C# files end with a *.cs file extension.
using System;
class HelloClass
{
public static int Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadLine();
return 0;
}
}
GRNICA 3
using System;
class HelloClass1
{
public static void Main(string[] args)
{
Console.WriteLine("Hello.... ");
Console.WriteLine(" "+args[0]);
Console.WriteLine(" "+args[1]);
}
}
Command line arguements
GRNICA 4
using System;
class HelloClass2
{
public static void Main(string[] args)
{
String name = "c sharp";
Console.WriteLine(name);
}
}
Using String objects in output
GRNICA 5
class TestClass
{
public void fun()
{
System.Console.WriteLine("hooooooooooooooo");
}
}
class HelloClass3
{
public static void Main(string[] args)
{
TestClass test = new TestClass();
test.fun();
}
}
A program with two classes
GRNICA 6
using System;
using System.Windows.Forms;
class HelloMessage
{
public void Speak()
{
MessageBox.Show("Hello...");
}
}
using System;
class TestApps
{
public static void Main()
{
Console.WriteLine("Testing! 1, 2, 3");
HelloMessage h = new HelloMessage();
h.Speak();
}
}
One more example.
GRNICA 7
using System;
class HelloClass6
{
public static void Main(string[] args)
{
Console.Write("Enter your name:");
String name = Console.ReadLine();
Console.WriteLine("Hello" + name);
}
}
Interactive console input
GRNICA 8
using System;
class HelloClass7
{
public static void Main(string[] args)
{
double x = 5.0,y;
y=Math.Sqrt(x);
Console.WriteLine(" Y = " + y);
}
}
Using Mathematics functions
GRNICA 9
Variations on the Main() Method
// No return type, array of strings as argument.
public static void Main(string[] args)
{
}

// No return type, no arguments.
public static void Main()
{
}

// Integer return type, no arguments.
public static int Main()
{
}
GRNICA 10
Processing Command-Line Arguments
// This time, check if you have been sent any command-line arguments.
using System;
class HelloClass
{
public static int Main(string[] args)
{
Console.WriteLine("***** Command line args *****");
for(int i = 0; i < args.Length; i++)
Console.WriteLine("Arg: {0} ", args[i]);
...
}
}

// Notice you have no need to check the size of the array when using 'foreach'.
public static int Main(string[] args)
{
...
foreach(string s in args)
Console.WriteLine("Arg: {0} ", s);
...
}
GRNICA 11
// Now using System.Environment.
string[] theArgs = Environment.GetCommandLineArgs();
Console.WriteLine("Path is: {0}", theArgs[0]);

for(int i=1; i < theArgs.Length; i++)
Console.WriteLine("Again, the args are {0}", theArgs[i]);
GRNICA 12
Creating Objects: Constructor Basics
A class is a definition of a user-defined type (UDT) that is often
regarded as a blueprint for variables of this type.

An object is simply a term describing a given instance of a particular
class.
In C#, the "new" keyword is the way to create an object instance.
//This is no good.
using System;
class HelloClass
{
public static int Main(string[] args)
{
Helloclass c1;
c1.SayHi();
return 0;
}
}
GRNICA 13
using System;
class HelloClass
{
public static int Main(string[] args)
{
HelloClass c1 = new HelloClass();
HelloClass c2 = new HelloClass();
return 0;
}
}
The "new" keyword is in charge of allocating the correct number
of bytes for the specified class and acquiring sufficient memory
from the managed heap.

C# object variables are actually a reference to the object in
memory, not the actual object itself.
GRNICA 14
The previous HelloClass objects have been constructed using the
default constructor, which by definition never takes arguments.

Every C# class is automatically provided with a free default
constructor, which you may redefine if need be.

The default constructor ensures that all member data is set to an
appropriate default value.
GRNICA 15
using System;
class HelloClass8
{
public HelloClass8()
{
Console.WriteLine("Default constructor called.");
}

public HelloClass8(int x, int y)
{
Console.WriteLine("Custom constructor called.");
intX = x;
intY = y;
}
public int intX, intY;

public static int Main(string[] args)
{
HelloClass8 c1 = new HelloClass8();
Console.WriteLine("c1.intX = {0} \n c1.intY = {1} \n",c1.intX, c1.intY);

HelloClass8 c2 = new HelloClass8(100,200);
console.WriteLine("c2.intX = {0} \nc2.intY = {1} \n", c2.intX, c2.intY);
return 0;
}
}
GRNICA 16
Is That a Memory Leak?
The Main() method of the previous HelloClass type has no logic that
explicitly destroys the c1 and c2 variables:
public static int Main(string[] args)
{
HelloClass8 c1 = new HelloClass8();
Console.WriteLine("c1.intX = {0} \n c1.intY = {1} \n",c1.intX, c1.intY);

HelloClass8 c2 = new HelloClass8(100,200);
console.WriteLine("c2.intX = {0} \nc2.intY = {1} \n", c2.intX, c2.intY);
return 0;
}
The .NET garbage collector frees the allocated memory
automatically, and therefore C# does not support a "delete
keyword.
GRNICA 17
The Composition of a C# Application
HelloClass8 type has been constructed to perform two duties.

First, the class defines the entry point of the application.

Second, HelloClass maintains two custom data members and a few
overloaded constructors.
GRNICA 18
class HelloClass
{
public string userMessage;
public HelloClass()
{ Console.WriteLine("Default ctor called!"); }
public HelloClass(string msg)
{
Console.WriteLine("Custom ctor called!");
userMessage = msg;
}
public void PrintMessage()
{
Console.WriteLine("Message is: {0}", userMessage);
}
}

class HelloApp
{
public static int Main(string[] args)
{
HelloClass c1 = new HelloClass("Hey there...");
c1.PrintMessage();
...
}
}
GRNICA 19
Default Assignments and Variable Scope
All intrinsic .NET data types have a default value. When custom
types are created, all member variables are automatically assigned to
their appropriate default value.
class DefaultValueTester
{
public sbyte theSignedByte;
public byte theByte;
public short theShort;
public ushort theUShort;
public int theInt;
public uint theUInt;
public long theLong;
public ulong theULong;
public char theChar;
public float theFloat;
public double theDouble;
public bool theBool;
public decimal theDecimal;
public string theStr;
public static int Main(string[] args)
{
DefaultValueTester v = new DefaultValueTester();
return 0;
}
}
GRNICA 20
When you define variables within a method scope, you must assign
an initial value before you use them, as they do not receive a default
assignment.
// Compiler error! Must assign localInt to an initial value before use.
public static void Main()
{
int localInt;
Console.WriteLine(localInt);
}
// Better. Everyone is happy.
public static void Main()
{
int localInt=0;
Console.WriteLine(localInt);
}

GRNICA 21
The C# Member Variable Initialization Syntax
A class may define various custom constructors, and its annoying
write the same initialization code in each and every constructor
implementation.

This is particularly necessary if you do not wish to accept the
default values assigned to your state data.
// This is OK, but redundant...
class Test
{
private int myInt;
Test() { myInt = 9; }
Test(string someStringParam)
{ myInt = 9; }
Test(bool someBoolParam)
{ myInt = 9; }
...
}
GRNICA 22
An alternative would be to define a private helper function for your
class type that is called by each constructor.
// This is OK, but redundant...
class Test
{
private int myInt;
Test() { InitData(); }
Test(string someStringParam)
{ InitData(); }
Test(bool someBoolParam)
{ InitData(); }
private void InitData()
{ myInt = 9; }
...
}
While both of these techniques are still valid, C# allows you to
assign a type's member data to an initial value at the time of
declaration.
GRNICA 23
// This technique is useful when you don't want to accept default values
// and would rather not write the same initialization code in each constructor.
class Test
{
private int myInt = 9;
private string myStr = "My initial value.";
private HotRod viper = new HotRod(200, "Chucky", Color.Red);
...
}
GRNICA 24
Basic Input and Output with the Console Class
The methods of System.Console are Read(), ReadLine() Write() and
WriteLine(), all of which are defined as static.

WriteLine() pumps a text string (including a carriage return)
to the output stream.

The Write() method pumps text to the output stream without a
carriage return.

ReadLine() allows you to receive information from the input stream
up until the carriage return.

Read() is used to capture a single character from the input stream.
GRNICA 25
//Make use of the Console class to perform basic IO.
using System;
class BasicIO
{
public static void Main(string[] args)
{
Console.Write("Enter your name:");
String s = Console.ReadLine();
Console.WriteLine("Hello, {0}",s);
Console.Write("Enter your age:");
s = Console.ReadLine();
Console.WriteLine("your are {0} years old", s);
}
}

GRNICA 26
Formatting Textual Output
//Make use of the Console class to perform basic IO.
using System;
class BasicIO
{
public static void Main(string[] args)
{
...
int theInt = 90;
float theFloat = 9.99;
BasicIO myIO = new BasicIO();
//Format a string....
Console.WriteLine("Int is : {0} \n Float is: {1} \n You Are: {2}",
theInt, theFloat, myIO.ToString());
}
}
WriteLine() has been over-loaded to allow you to specify
placeholder values as an array of objects.
GRNICA 27
// Fill placeholders using an array of objects.

object[] stuff = {"Hello", 20.9, 1, "There", "83", 99.99933} ;

Console.WriteLine("The Stuff: {0} , {1} , {2} , {3} , {4} , {5} ", stuff);
If you want to build the string "9Number9Number9 write as below
Console.WriteLine("{0}Number{0}Number{0}", 9);
GRNICA 28
String Formatting Flags
.NET String Format Characters
These format characters are suffixed to a given placeholder using
the colon token (for example, {0:C}, {1:d}, {2:X}, and so on).
GRNICA 29
// Now make use of some format tags.
using System;
class hi
{

public static void Main(string[] args)
{
Console.WriteLine("C format: {0:C}", 99989.987);
Console.WriteLine("D9 format: {0:D9}", 99999);
Console.WriteLine("E format: {0:E}", 99999.76543);
Console.WriteLine("F3 format: {0:F3}", 99999.9999);
Console.WriteLine("N format: {0:N}", 99999);
Console.WriteLine("X format: {0:X}", 99999);
Console.WriteLine("x format: {0:x}", 99999);
}
}
GRNICA 30
The use of the C# formatting characters is not limited to the
System.Console.WriteLine() method.

For example, these same flags can be used within the context of
the static String.Format() method.

This can be helpful when you need to build a string containing
numerical values in memory and display it at a later time:
// Use the static String.Format() method to build a new string.

string formStr;

formStr = String.Format("Don't you wish you had {0:C} in your account?", 99989.987);

Console.WriteLine(formStr);
GRNICA 31
Understanding Value Types and Reference Types
A .NET data type may be value-based or reference-based.

Value-based types include all numerical data types (int, float..) as
well as enumerations and structures, are allocated on the stack.

Value types can be quickly removed from memory once they fall out
of the defining scope:
//Integers are value types!
public void SomeMethod()
{
int i = 0;
Console.WriteLine(i);
}// 'i' is popped off the stack here!
GRNICA 32
// Assigning two intrinsic value types results in two independent variables on the
stack.

public void SomeMethod()
{
int i = 99;
int j = i;
// After the following assignment, i is still 99.
j = 8732;
}
GRNICA 33
using System;
// Structures are value types!
struct FOO
{
public int x, y;
}

class ValRefClass
{
public static int Main(string[] args)
{
FOO f1 = new FOO();
f1.x = 100;
f1.y = 100;
Console.WriteLine("-> Assigning f2 to f1\n");
FOO f2 = f1;
//Here is F1.
Console.WriteLine("F1.x = {0}", f1.x);
Console.WriteLine("F1.y = {0}", f1.y);
//Here is F2.
Console.WriteLine("F2.x = {0}", f2.x);
Console.WriteLine("F2.y = {0}", f2.y);
//Change f2.x. This will not change f1.x
Console.WriteLine("->Changing f2.x to 900");
f2.x=900;
//Print again.
Console.WriteLine("F2.x = {0}", f2.x);
Console.WriteLine("f1.x = {0}", f1.x);
return 0;
}
}
GRNICA 34
In contrast, reference types are allocated on the garbage-collected
heap.
These entities stay in memory until the .NET garbage collector
destroys them.
Assignment of reference types results in a new reference to the
same object in the memory.
using System;
// Classes are always reference types.
class FOO
{
public int x, y;
}
GRNICA 35
class ValRefClass
{
public static int Main(string[] args)
{
FOO f1 = new FOO();
f1.x = 100;
f1.y = 100;
Console.WriteLine("-> Assigning f2 to f1\n");
FOO f2 = f1;
//Here is F1.
Console.WriteLine("F1.x = {0}", f1.x);
Console.WriteLine("F1.y = {0}", f1.y);
//Here is F2.
Console.WriteLine("F2.x = {0}", f2.x);
Console.WriteLine("F2.y = {0}", f2.y);
//Change f2.x. This will not change f1.x
Console.WriteLine("->Changing f2.x to 900");
f2.x=900;
//Print again.
Console.WriteLine("F2.x = {0}", f2.x);
Console.WriteLine("f1.x = {0}", f1.x);
return 0;
}
}
GRNICA 36
Value Types Containing Reference Types
Assume you have the following reference (class) type:
class ShapeInfo
{
public string infoString;
public ShapeInfo(string info)
{ infoString = info; }
}
Now assume that you want to contain a variable of this reference
type within a value type (structure).
GRNICA 37
struct MyRectangle
{
// The MyRectangle structure contains a reference type member.
public ShapeInfo rectInfo; //Refrence type.
public int top, left, bottom, right; //Value type.
public MyRectangle(string info)
{
rectInfo = new ShapeInfo(info);
top = left = 10;
bottom = right = 100;
}
}
GRNICA 38
class reference1
{
static void Main(string[] args)
{
// Create the first MyRectangle.
Console.WriteLine("-> Creating r1");
MyRectangle r1 = new MyRectangle("This is my first rect");

// Now assign a new MyRectangle to r1.
Console.WriteLine("-> Assigning r2 to r1");
MyRectangle r2;
r2 = r1;

// Change values of r2.
Console.WriteLine("-> Changing all values of r2");
r2.rectInfo.infoString = "This is new info!";
r2.bottom = 4444;

// Print values
Console.WriteLine("-> Values after change:");
Console.WriteLine("-> r1.rectInfo.infoString: {0}", r1.rectInfo.infoString);
Console.WriteLine("-> r2.rectInfo.infoString: {0}", r2.rectInfo.infoString);
Console.WriteLine("-> r1.bottom: {0}", r1.bottom);
Console.WriteLine("-> r2.bottom: {0}", r2.bottom);
}
}
GRNICA 39
Value and Reference Types: Final Details
Value Types and Reference Types Side by Side
GRNICA 40
GRNICA 41
The Master Node: System.Object
In C#, every data type (value or reference based) is ultimately
derived from a common base class: System.Object.
The Object class defines a common polymorphic behavior for every
type in the .NET universe.




If you wish to explicitly state System.Object as your base class, you
are free to define your class definitions using either of the following
notations:

// Here we are explicitly deriving from System.Object.
class HelloClass : System.Object {...}
//same story here...
class HelloClass : object{...}
// Implicitly deriving from System.Object.
class HelloClass {...}
GRNICA 42
Like most .NET classes, System.Object defines a set of instance-
level and class-level (static) members.
Note that some of these items are declared "virtual," and can
therefore be overridden by a derived class:
// The topmost class in the .NET world: System.Object
namespace System
{
public class Object
{
public Object();
public virtual Boolean Equals(Object obj);
public virtual Int32 GetHashCode();
public Type GetType();
public virtual String ToString();
protected virtual void Finalize();
protected Object MemberWiseClone();
public static bool Equals(object objA, object objB);
public static bool ReferenceEquals(object objA, object objB);
}
}
GRNICA 43
Core Members of System.Object
GRNICA 44
GRNICA 45
// Create some objects and exercise the inherited System.Object methods.
using System;
class ObjTest
{
public static int Main(string[] args)
{
// Make an instance of ObjTest.
ObjTest c1 = new ObjTest();
// Pump info to console.
Console.WriteLine("ToString: {0} ", c1.ToString());
Console.WriteLine("Hash code: {0} ", c1.GetHashCode());
Console.WriteLine("Base class: {0} ", c1.GetType().BaseType);
// Make some other references to c1.
ObjTest c2 = c1;
object o = c2;
// Are all 3 instances pointing to the same object in memory?
if(o.Equals(c1) && c2.Equals(o))
Console.WriteLine("Same instance!");
return 0;
}
}
Derived classes override this
method to return a string
representing the values of its
internal state data.
Returns an integer that
identifies a specific object
instance.
GetType() retrieves a
System.Type object, which
defines a property named
BaseType.
The default behavior of Equals() is
to compare two objects' variables
using reference semantics not value
semantics.
GRNICA 46
Overriding Some Default Behaviors of System.Object
Although the System.Object can be used in number of cases, it is
quite common for your custom types to override some of these
inherited methods.

System.Object defines a number of virtual methods (such as
ToString() and Equals()) that do define a canned implementation.

However, if you want to build a custom implementation of these
virtual members for a derived type, you make use of the C#
"override" keyword.
GRNICA 47
To illustrate, assume you have a Person class that defines some state data
representing an individual's name, social security number, and age:
// Remember! All classes implicitly derive from System.Object.
class Person
{
public Person(string fname, string lname, string ssn, byte a)
{
firstName = fname;
lastName = lname;
SSN = ssn;
age = a;
}
public Person(){}
// The state of a person.
public string firstName;
public string lastName;
public string SSN;
public byte age;
}

GRNICA 48
Overriding ToString()
lets override System.Object.ToString() to return a textual
representation of a persons state:
// Need to reference this namespace to access StringBuilder type.
using System.Text;
// A Person Class implements ToString() as so:
class Person
{
//Overriding System.Object.ToString().
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("[FirstName = {0}", this.firstName);
sb.AppendFormat(" LastName = {0}", this.lastName);
sb.AppendFormat(" SSN = {0}", this.SSN);
sb.AppendFormat(" Age = {0}]", this.age);
return sb.ToString();
}
...........
}
GRNICA 49
GRNICA 50
GRNICA 51
GRNICA 52

You might also like