Beruflich Dokumente
Kultur Dokumente
C# Language Fundamentals
OBJECTIVES
Basic C# Class Constructors Basic Input and Output Value Types and Reference Types Iteration Statements Control Flow Statements Static Methods and Parameter passing Methods Arrays, Strings, and String Manipulations Enumerations and Structures
Basic C# Class
// Hello.cs using System;
class HelloClass { public static int Main(string[ ] args) { Console.WriteLine("Hello World"); return 0; } }
{ public static int Main(string[ ] args) { Console.WriteLine("Command Line parameters"); for (int x = 0; x < args.Length; x++) // foreach (string s in args) Console.WriteLine("Args: {0}", args[x]); return 0; } }
CONSTRUCTORS
Works almost same as C++ "new" is the de facto standard to create an object instance Example ( illegal ) Correct version
EXAMPLE (Point.cs)
class Point { public Point() { Console.WriteLine("Default Constructor"); } public Point(int px, int py) { x = px; y = py; } public int x; public int y; } class PointApp { public static void Main(string[ ] args) { Point p1 = new Point(); // default constructor called Point p2; p2 = new Point(10, 20); // one arg constructor called
Default Values
Example
string):
// RW.cs using System;
} }
Basic IO
// IO.cs using System; class BasicIO { public static void Main(string[ ] args) { int theInt = 20; float theFloat = 20.2F; // double theFloat = 20.2; is OK string theStr = "BIT"; Console.WriteLine("Int: {0}", theInt); Console.WriteLine("Float: {0}", theFloat); Console.WriteLine("String: {0}", theStr); // array of objects object[ ] obj = {"BIT", 20, 20.2};
Example // Format.cs using System; class Format { public static void Main (string [ ] args) { Console.WriteLine("C Format: {0:c}", 9999); Console.WriteLine("D Format: {0:d}", 9999); Console.WriteLine("E Format: {0:e}", 9999); Console.WriteLine("F Format: {0:f}", 9999); Console.WriteLine("G Format: {0:g}", 9999); Console.WriteLine("N Format: {0:n}", 9999); Console.WriteLine("X Format: {0:x}", 9999); } }
or reference type Primitive types are always value types including structures These types are allocated on the stack. Outside the scope, these variables will be popped out. However, classes are not value type but reference based
Example - 1
public void SomeMethod() { int i = 30; // i is 30 int j = i; // j is also 30 int j = 99; // still i is 30, changing j will not change i }
Example - 2
struct Foo { public int x, y; }
public void SomeMethod() { Foo f1 = new Foo(); // assign values to x and y Foo f2 = f1; // Modifying values of f2 members will not change f1 members . }
Class Types
Class types are always reference types These are allocated on the garbage-collected heap Assignment of reference types will
Now the statement Foo f2 = f1; has a reference to the object f1 and any changes made for f2 will change f1
Example
// ValRef.cs // This is a Reference type because it is a class
struct InnerRef { public TheRefType refType; // ref type public int structData; // value type public InnerRef(string s) { refType = new TheRefType(s); structData = 9; } }
System.Object
Every C# data type is derived from the base class called System.Object
Example
namespace System
{
public Object(); public virtual Boolean Equals(Object(obj); public virtual Int32 GetHashCode(); public Type GetType();
.. } }
Core Members of
Example ToString(), Equals(), etc. class Person { public Person(string fname, string lname, string ssn, byte a) { firstName = fname; lastName = lname; SSN = ssn; age = a; } public Person() { } public string firstName, lastName, SSN; public byte age; }
Overriding ToString()
using System.Text;
class Person { public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("[FName =
{0}", this.firstName); sb.AppendFormat("LName = {0}", this.lastName); sb.AppendFormat("SSN = {0}", this.SSN); sb.AppendFormat("Age = {0}]", this.age); return sb.ToString(); } }
Overriding Equals()
Equals() returns true if and only if the two objects being compared reference the same object in memory We can override this behavior and design when two objects have the same value (valuebased). That is, when name, SSN, age of two objects are equal, then return true else
return false.
Example
class Person { public override bool Equals(object o) { Person temp = (Person) o; if (temp.firstName == this.firstName && temp.lastName == this.lastName && temp.SSN == this.SSN && temp.age == this.age) return true; else return false; } }
Overriding GetHashCode()
should also override GetHashCode() Returns All custom types will be put in a System.Collections.Hashtable type. The Equals() and GetHashCode() methods will be called behind the scene to determine the correct type to return from the container Generation of hash code can be customized. In our example we shall use SSN a String member that is expected to be unique Example: refer to: Override.cs
public override int GetHashCode()
{ return SSN.GetHashCode(); }
C# Data Types
Integers
UInt16.MaxValue UInt16.MinValue
Double
Boolean
bool.FalseString bool.TrueString
Examples
Char
Value Type
Value types are used directly by their values int, float, char, enum, etc. are value types These types are stored in a Stack based memory Example: int Age = 42; or int Age = new int(42);
Reference Type
These types are allocated in a managed Heap Objects of these types are indirectly referenced Garbage collection is handled by .NET
Boxing
Explicitly converting a value type into a corresponding reference type Example: int Age = 42; object objAge = Age; No need for any wrapper class like Java C# automatically boxes variables whenever needed. For example, when a value type is passed to a method requiring an object, then boxing is done automatically.
UnBoxing
Converting the value in an object reference (held in heap) into the corresponding value type (stack) Example:
object objAge; int Age = (int) objAge; // OK string str = (string) objAge; // Wrong!
C# Iteration Constructs
for loop foreach-in loop while loop do-while loop
languages
StreamReader strReader = File.OpenText("d:\\in.dat"); string strLine = null; while (strReader.ReadLine( ) != null) { Console.WriteLine(strLine); } strReader.Close(); } catch (FileNotFoundException e) { Console.WriteLine(e.Message); } }
Control Statements
if, if-else Statements Relational operators like ==, !=, <, >, <=, >=, etc are all allowed in C# Conditional operators like &&, ||, ! are also allowed in C# Beware of the difference between int and bool in C# Example
string s = "a b c"; if (s.Length) Error! { . }
goto Statement
goto label; Explicit fall-through in a switch statement can be achieved by using goto statement Example:
C# Operators
All operators that you have used in C and C++ can also be used in C# Example: +, -, *, /, %, ?:, ->, etc Special operators in C# are : typeof, is and as The is operator is used to verify at runtime whether an object is compatible with a given type The as operator is used to downcast between types The typeof operator is used to represent runtime type information of a class
Example - is
public void DisplayObject(object obj)
{ if (obj is int) Console.WriteLine("The object is of type integer"); else Console.WriteLine("It is not int"); }
Example - as
Using as, you can convert types without raising an exception In casting, if the cast fails an InvalidCastException is raised But in as no exception is raised, instead the reference will be set to null
static void ChaseACar(Animal anAnimal) { Dog d = anAnimal as Dog; // Dog d = (Dog) anAnimal; if (d != null)
Example - typeof
Typeof.MyClass
Access Specifiers
public void MyMethod() { }
Accessible anywhere private void MyMethod() { } Accessible only from the class where defined
Accessible from its own class and its descendent internal void MyMethod() { } Accessible within the same Assembly void MyMethod() { } private by default protected internal void MyMethod() { }
Access is limited to the current assembly or types derived from the containing class
Static Methods
What does 'static' method mean? Methods marked as 'static' may be called from class level This means, there is no need to create an instance of the class (i.e. an object variable) and then call. This is similar to
Console.WriteLine() public static void Main() why static? At run time Main() call be invoked without any object variable of the enclosing class
Example
public class MyClass { public static void MyMethod() {} } public class StaticMethod { public static void Main(string[ ] args) { MyClass.MyMethod(); } }
public class Stack { public static void Push(string s) { items[++top] = s; } public static string Pop() { return (items[top--]); } public static void Show() { for (int i = top; i >= 0; i--) Console.WriteLine(items[i]); } private static string[ ] items = new string[5]; private static int top = -1; }
Stack Class.
class StaticMethod { public static void Main(string[] args) { Console.WriteLine("Stack Contents:"); Stack.Push("BIT");
Parameter Passing
type is that we can return more than one value from the called program to the caller
parameters in a Method declaration The params parameter must be a single dimensional array (else you get an error) You can define any object in the parameter list
Example
using System; class Params { public static void DispArrInts(string msg, params int[ ] list) { Console.WriteLine(msg); for (int i = 0; i < list.Length; i++) Console.WriteLine(list[i]); } static void Main(string[ ] args) { int[ ] intArray = new int[ ] {1, 2, 3}; DispArrInts("List1", intArray); DispArrInts("List2", 4, 5, 6, 7); // you can send more elements DispArrInts("List3", 8,9); // you can send less
elements } }
Instead of using only an integer list for the params parameter, we can use an object (Refer to ParamsMethod folder)
public class Person { private string name; private byte age; public Person(string n, byte a) { name = n; age = a; } public void PrintPerson() { Console.WriteLine("{0} is {1} years old", name, age); } }
for (int i = 0; i < list.Length; i++) { if (list[i] is Person) ((Person)list[i]).PrintPerson(); else Console.WriteLine(list[i]); } Console.WriteLine(); }
If a reference type is passed by value, the calling program may change the value of the object's state data, but may not change the object it is referencing (Refer to PassingRefTypes folder) public static void PersonByValue(Person p) { // will change state of p
p.age = 60; // will not change the state of p p = new Person("Nikki", 90);
If a class type is passed by reference, the calling program may change the object's state data as well as the object it is referencing public static void PersonByRef(ref Person p) { // will change state of p p.age = 60; // p will point to a new object p = new Person("Nikki", 90); }
// Pass by Value
Calling Program
Console.WriteLine("Passing By Value..........."); Person geetha = new Person("Geetha", 25); geetha.PrintPerson(); PersonByValue(geetha); geetha.PrintPerson(); // Pass by Reference Console.WriteLine("Passing By Reference........"); Person r = new Person("Geetha", 25); r.PrintPerson(); PersonByRef(ref r); r.PrintPerson();
Arrays in C#
C# arrays are derived from System.Array base class Memory for arrays is allocated in heap It works much same as C, C+ +, Java, etc. Example
string[10]; // string array int [ ] intArray = new int [10]; // integer array int[2] Age = {34, 70}; // Error, requires new keyword Person[ ] Staff = new Person[2]; // object array strAarray[0] = "BIT"; // assign some value int [ ] Age = new int[3] {25, 45, 30}; // array initialization
Example
public static int[ ] ReadArray( ) // reads the elements of the array { int[ ] arr = new int[5]; for (int i = 0; i < arr.Length; i++) arr[i] = arr.Length - i; return arr; } public static int[ ] SortArray(int[ ] a) { System.Array.Sort(a); // sorts an array return a;
Multidimensional Arrays
Rectangular Array
Jagged Array
for (int i=0; i < myJaggedArr.Length; i++) myJaggedArr[i] = new int[i + 7]; Note that, 1st row will have 7 columns and 2nd row will have 8 columns
Calling Program
public static void Main(string[ ] args) { int[ ] intArray; intArray = ReadArray( ); // read the array elements Console.WriteLine("Array before sorting"); for (int i = 0; i < intArray.Length; i++) Console.WriteLine(intArray[i]); intArray = SortArray(intArray); // sort the elements Console.WriteLine("Array after sorting"); for (int i = 0; i < intArray.Length; i++) Console.WriteLine(intArray[i]); }
String Manipulations in C#
A string is a sequential collection of
Unicode characters, typically used to represent text, while a String is a sequential collection of System.Char objects that represents a string. If it is necessary to modify the actual contents of a string-like object, use the System.Text.StringBuilder class. Members of String perform either an
ordinal or linguistic operation on a String. ordinal: acts on the numeric value of each
Char object. linguistic: acts on the value of the String taking into account culture-specific casing, sorting, formatting, and parsing rules.
of Unicode characters and how two strings compare to each other. For example, the Compare method performs a
linguistic comparison while the CompareOrdinal method performs an ordinal comparison. Consequently, if the current culture is U.S. English, the Compare method considers 'a' less than 'A' while the CompareOrdinal method considers 'a' greater than 'A'.
Strings
else if (y > 0) Console.WriteLine("a > A"); else Console.WriteLine("a < A"); Ouput: Ordinal a>A Compare a<A
Example: s = s.ToUpper();
System.Text.StringBuilder
Like Java, C# strings are immutable. This means, strings can not be modified once established For example, when you send ToUpper() message to a string object, you are not modifying the underlying buffer of the existing string object. Instead, you return a fresh copy of the buffer in uppercase It is not efficient, sometimes, to work on copies of strings solution? Use StringBuilder from System.Text!
Note: A String is called immutable because its
value cannot be modified once it has been created. Methods that appear to modify a String actually return a new String containing the modification. If it is necessary to modify the actual contents of a string-like object, use the System.Text.StringBuilder class.
Example
using System; using System.Text; class MainClass { public static void Main() { StringBuilder myBuffer = new StringBuilder("Buffer"); // create the buffer or string builder myBuffer.Append( " is created"); Console.WriteLine(myBuffer); // ToString() converts a StringBuilder to a string string uppercase = myBuffer.ToString().ToUpper(); Console.WriteLine(uppercase); string lowercase = myBuffer.ToString().ToLower(); Console.WriteLine(lowercase); }
Enumerations in C#
Example - 1
Example - 2
enum Colors
{ Red = 10, // 10 Green, // 11 Blue // 12 }
Using Enumerations
Example
Array obj = Enum.GetValues(typeof(Colors)); foreach(Colors x in obj) { Console.WriteLine(x.ToString()); Console.WriteLine("int = {0}", Enum.Format(typeof(Colors), x, "D")); } Output
Red int = 0 Blue int = 1 Green int = 2
Structures in C#
default constructors It can implement interfaces Can have methods in fact, many! There is no System.Structure class!
Example
using System; struct STUDENT { public int RegNo; public string Name; public int Marks; public STUDENT(int r, string n, int m) { RegNo = r; Name = n; Marks = m; } } class MainClass { public static void Main() { STUDENT Geetha;
Geetha.RegNo = 111; Geetha.Name = "Geetha"; Geetha.Marks = 77; } } STUDENT SomeOne = new STUDENT(222,"Raghu",90);
Example
Assume that you are developing a collection of graphic classes: Square, Circle, and Hexagon
Alternate Approach
// Square.cs using System; namespace MyShapes { class Square { } } // Circle.cs using System; namespace MyShapes { class Circle { } } // Heagon.cs using System; namespace MyShapes { class Hexagon { }
MyShapes using System; using MyShapes; namespace MyApplication { class ShapeDemo { .. Square sq = new Square(); Circle Ci = new Circle(); Heagone he = new Heagon(); . } } defined in MyShapes namespace
Qualify the name of the class with the appropriate namespace The default namespace given in VS IDE is the name of the project
End of
Chapter 3