Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Language.

Similar presentations


Presentation on theme: "C# Language."— Presentation transcript:

1 C# Language

2 Table of Contents Properties Indexer Attributes Reflection API
Delegates Enums , jagged Arrays The params parameter Unsafe code, unchecked code Call by value and reference

3 Definition of Property
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.  For example, let us have a class named Student, with private fields for age, name, and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields.

4 Properties Property is a member that provides access to an attribute of a class. Unlike fields, properties are not used to declare storage locations. It provides a mechanism for associating actions with the reading and writing of private fields of an object or a class.

5 Accessors Get accessor reads and performs computations on the data elements , whereas the set accessor writes the data element.

6 ‘get’ accessor private string bookname; public string Name { get
return bookname; }

7 When you reference a property, except as target of an assignment , the get accessor is invoked to read the value of the property. The get accessor must terminate with return or throw statement.

8 ‘set’ accessor public string Name { get return bookname; } set
bookname= value;

9 The set accessor is similar to a method that returns void.
It uses an implicit parameter called value, whose type is the type of property. When you assign a value to the property, set accessor is invoked with an argument that provides new value.

10 Read Only and Write Only
A property with only a get accessor is called a read only property. You can not assign a value to read only property. A property with only a set accessor is called a write only property. You can not reference a write only property except as a target of an assignment.

11 Access Modifier of Properties
‘get’ and ‘set’ can have different modifiers. But access modifier of one of them must be same as that of property. Else compiler will generate error. By default it is public. Let us see example.

12 public string Name { get return bookName; } private set bookName = value;

13 Specifying properties in an interface
interface Shape { int Sides get; set; } double area();

14 class Squarem : Shape { private int Sqsides; public int l; public double Area() return ((double) l * l); } public int Sides get return Sqsides; set Sqsides = value;

15 Indexer

16 What is Indexer? An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. Indexer is smart array that allow user to use an index on an object to obtain values. An indexer is an element that enables instances of classes, structs to be indexed or categorized in the same way as array. Declaring an indexer enables you to create classes that are like virtual arrays.

17 Indexer and properties
* 07/16/96 Indexer and properties It is similar to property : You can get and set when defining an indexers Unlike properties : you are not obtaining a specific data member instead of it, you are obtaining a value from object itself (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

18 Property : you define a name
Indexer : we use this keyword, which refers to the object instance Accessor declarations are indexer accessors that specify the executable statements corresponding to the reading and writing indexer elements.

19 * 07/16/96 indexer declaration <access modifier> <return type> this [argument] { get { } set{ (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

20 Difference between Indexers and Properties  
1) Indexers are created with this keyword. Properties don't require this keyword. 2) Indexers are identified by signature. Properties are identified by their names. 3) Indexers are accessed using indexes. Properties are accessed by their names.

21 4) Indexer are instance member, so can't be static.
Properties can be static as well as instance members. 5) A get accessor of an indexer has the same formal parameter list as the indexer. A get accessor of a property has no parameters. 6) A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter. A set accessor of a property contains the implicit value parameter.

22 What They Are? How and When to Use Them?
* Attributes What They Are? How and When to Use Them? (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

23 * What Are Attributes? Special declarative tags for attaching descriptive information to the declarations in the code At compile time attributes are saved in the assembly's metadata Can be extracted from the metadata and can be manipulated by different tools Instances of classes derived from System.Attribute (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

24 Attributes Applying – Example
* Attributes Applying – Example Attribute's name is surrounded by square brackets and is placed before the element to which attribute is applied : Attributes use parameters for initialization [attribute(positional_parameters, name_parameter = value, ...)] element (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

25 Types of Attributes Pre-defined attributes Custom built attributes
* Types of Attributes Pre-defined attributes The .Net Framework provides pre-defined attributes like…. AttributeUsage Obsolete Custom built attributes (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

26 AttributeUsage The pre-defined attribute AttributeUsage specifies the types of items to which the custom attribute can be applied. Syntax for specifying this attribute is as follows: [AttributeUsage ( validon, AllowMultiple=allowmultiple, Inherited=inherited )]

27 validon The parameter validon
specifies the language elements on which the attribute can be placed. It is a combination of the value of an enumerator AttributeTargets. The default value is AttributeTargets.All.

28  allowmultiple  The parameter allowmultiple (optional) provides value for theAllowMultiple property of this attribute, a Boolean value. If this is true, the attribute is multiuse. The default is false (single-use).

29 inherited The parameter inherited (optional) provides value for the Inherited property of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes. The default value is false (not inherited).

30 Example [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]

31 Obsolete enables you to inform the compiler to discard a particular target element The parameter message, is a string describing the reason  The parameter iserror, is a Boolean value. [Obsolete( message, iserror )]

32 Types of Parameter Named Positional (essential information) Optional
* Types of Parameter Named Optional Positional (essential information) Specific order [attribute(positional_parameters, name_parameter = value, ...)] element (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

33 Code… using System; namespace AttributeDemo {
* Code… using System; namespace AttributeDemo { [AttributeUsage(AttributeTargets.Class)] class ClassInfo : Attribute int ver; string desc; public ClassInfo(string d) desc = d; } public int Version get { return ver; } set { ver = value; } (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

34 Code… [ClassInfo("This is demo Class",Version=5)] class Student {
* Code… [ClassInfo("This is demo Class",Version=5)] class Student { [Obsolete("Dont use this")] public void Result() Console.WriteLine("Result"); } class Program static void Main() Student s1 = new Student(); s1.Result(); Console.ReadLine(); (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

35 Reflection API

36 * 07/16/96 Reflection API Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application. (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

37 Reflection Namespace and Class
* 07/16/96 Reflection Namespace and Class System.Reflection namespace contains following reflection related classes. Assembly class Module class ConstructorInfo, MethodInfo, FieldInfo, EventInfo, PropertyInfo, ParameterInfo class (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

38 Application of Reflection
It allows view attribute information at runtime. It allows examining various types in an assembly and instantiate these types. It allows late binding to methods and properties It allows creating new types at runtime and then performs some tasks using those types.

39 Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, module and type information at runtime. By using Reflection in c#, one is able to find out details of an object, method and create objects and invoke methods at runtime.

40 Common Methods GetTypes() GetMethods() GetConstructors()
* 07/16/96 Common Methods GetTypes() GetMethods() GetConstructors() GetProperties() GetEvents() GetInterfaces() (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

41 GetMethod() returns a reference to a System. Reflection
GetMethod() returns a reference to a System.Reflection.MethodInfo object, which contains details of a method. Searches for the public method with the specified name. GetMethods() returns an array of such references. The difference is that GetMethods() returns details of all the methods, whereas GetMethod() returns details of just one method with a specified parameter list.

42

43 Delegates and Events (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

44 What are Delegates? C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. The delegate object can be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

45 * Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class. A delegate also can be described as a template for a method. Though a delegate specifies the return type and signature., it is implemented by the method. (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

46 Declaring a delegate A delegate can refer to a method, which has the same signature as that of the delegate. For example, consider a delegate: public delegate int MyDelegate (string s); The preceding delegate can be used to reference any method that has a single string parameter and returns an int type variable.

47 syntax delegate <return type> <delegate-name> <parameter list>

48 Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. For example: public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen);

49 Delegates – Example // Declaration of a delegate
* Delegates – Example // Declaration of a delegate public delegate void SimpleDelegate(string param); public class TestDelegate { public static void TestFunction(string param) Console.WriteLine("I was called by a delegate."); Console.WriteLine("I got parameter {0}.", param); } public static void Main() // Instantiation of а delegate SimpleDelegate simpleDelegate = new SimpleDelegate(TestFunction); // Invocation of the method, pointed by a delegate simpleDelegate("test"); (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

50 Using Delegates: Standard Way
* Using Delegates: Standard Way class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() SomeDelegate dlg = new SomeDelegate(SomeMethod); dlg("Hello"); } void SomeMethod(string str) Console.WriteLine(str); (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

51 Multicasting a Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate.

52 Using this property of delegates you can create an invocation list of methods that will be called when a delegate is invoked. This is called multicasting of a delegate.

53 * Events In component-oriented programming the components send events to their owner to notify them when something happens E.g. when a button is pressed an event is raised The object which causes an event is called event sender The object which receives an event is called event receiver In order to be able to receive an event the event receivers must first "subscribe for the event" (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

54 * Events in .NET In the component model of .NET Framework delegates and events provide mechanism for: Subscription to an event Sending an event Receiving an event Events in C# are special instances of delegates declared by the C# keyword event Example (Button.Click): public event EventHandler Click; (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

55 * Events in .NET (2) The C# compiler automatically defines the += and -= operators for events += subscribe for an event -= unsubscribe for an event There are no other allowed operations Example: Button button = new Button("OK"); button.Click += delegate { Console.WriteLine("Button clicked."); }; (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

56 * Events vs. Delegates Events are not the same as member fields of type delegate The event is processed by a delegate Calling of an event can only be done in the class it is defined in public MyDelegate m; public event MyDelegate m; (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

57 System.EventHandler Delegate
* System.EventHandler Delegate Defines a reference to a callback method, which handles events No additional information is sent Used in many occasions internally in .NET E.g. in ASP.NET and Windows Forms The EventArgs class is base class with no information about the event public delegate void EventHandler( Object sender, EventArgs e); (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

58 EventHandler – Example
* EventHandler – Example public class Button { public event EventHandler Click; public event EventHandler GotFocus; public event EventHandler TextChanged; ... } public class ButtonTest private static void Button_Click(object sender, EventArgs eventArgs) Console.WriteLine("Call Button_Click() event"); public static void Main() Button button = new Button(); button.Click += Button_Click; (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

59 Unsafe Code

60 Unsafe Code Use unsafe keyword to specify unsafe code block
* 07/16/96 Unsafe Code Use unsafe keyword to specify unsafe code block Use unsafe keyword at the time of compilation csc file.cs unsafe unsafe { int i; int *p; p = &i; } (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

61 Code… Assembly a = Assembly.LoadFrom("Assembly_Path");
* 07/16/96 Code… Assembly a = Assembly.LoadFrom("Assembly_Path"); Type[] types = a.GetTypes(); foreach (Type t in types) { Console.WriteLine(t.Name); MethodInfo[] mi = t.GetMethods(); foreach (MethodInfo m in mi) Console.WriteLine("- {0}",m.Name); ParameterInfo[] pi = m.GetParameters(); foreach (ParameterInfo p in pi) Console.WriteLine("-- {0}", p.ParameterType); } (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

62 The Paradigm of Exceptions in OOP
* Exceptions Handling The Paradigm of Exceptions in OOP (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

63 What are exceptions? An error at runtime

64 RunTime Errors Exception is a runtime error arises because of some abnormal conditions Such as – division of a number by Zero Passing a string to a variable that holds an integer value Accessing an array by invalid index

65 Compile time errors As compile time errors- occurs during compilation of a program Can happen due to bad coding and incorrect syntax Can correct these errors after looking at the error message that compiler generates On other hand, runtime errors that occur during execution of a program To prevent such types of errors two aspects

66 1) Find out those parts of a program which can cause runtime errors
2) How to handle those errors when they occur

67 In dot net, every exception is an object of type System
In dot net, every exception is an object of type System.Exception or of it’s subclass only Why an exception is an object? Purpose of exception handing is to resolve the error and let the program to continue from where it had a problem This we can do only if we get detailed information about error situation

68 So exception as an object can encapsulate all the data which is required for properly handling an exception in the catch block Basically exception handling is done using try and catch block

69 Some of the Exception Classes
DivideByZeroException FormatException IndexOutOfRangeException NullReferenceException ArithmeticException

70 The try…catch… finally statements
try block encloses those statements that can cause exception, whereas the catch block encloses the statements to handle the exception Multiple catch blocks can exist for a single try block All catch blocks are used to handle different types of exceptions raised inside the try block

71 * Handling Exceptions In C# the exceptions can be handled by the try-catch-finally construction catch blocks can be used multiple times to process different exception types try { // Do some work that can raise an exception } catch (SomeException) // Handle the caught exception (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

72 Finally block The statements enclosed in finally block are always executed, irrespective of the fact that whether n exception is occurs or not. Only one finally block for a try block If any exception occurs in try block, program control transfer to catch and then finally If no exception occurs inside try block, the program control is transferred to finally block.

73 Handling Exceptions – Example
static void Main() { string s = Console.ReadLine(); try Int32.Parse(s); Console.WriteLine( "You entered valid Int32 number {0}.", s); } catch (FormatException) Console.WriteLine("Invalid integer number!"); catch (OverflowException) "The number is too big to fit in Int32!");

74 The System.Exception Class
Exceptions in .NET are objects The System.Exception class is base for all exceptions in CLR Contains information for the cause of the error or the unusual situation Message – text description of the exception StackTrace – the snapshot of the stack at the moment of exception throwing

75 Exception Properties – Example
class ExceptionsTest { public static void CauseFormatException() string s = "an invalid number"; Int32.Parse(s); } static void Main() try CauseFormatException(); catch (FormatException fe) Console.Error.WriteLine("Exception caught: {0}\n{1}", fe.Message, fe.StackTrace);

76 * Exception Hierarchy Exceptions in .NET Framework are organized in a hierarchy (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

77 Throw keyword In C#, it is also possible to throw an exception programmatically. We can use throw statement to throw a user- defined exception. The throw statement takes only a single argument to throw an exception. When throw statement is encountered , program terminates.

78 * Throwing Exceptions Exceptions are thrown (raised) by throw keyword in C# Used to notify the calling code in case of error or unusual situation When an exception is thrown: The program execution stops The exception travels over the stack until a suitable catch block is reached to handle it Unhandled exceptions display error message (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

79 How Exceptions Work? Method N Method N … … Method 2 Method 2 Method 1
5. Throw an exception Method N Method N 4. Method call 6. Find handler Method 2 Method 2 3. Method call 7. Find handler Method 1 Method 1 2. Method call 8. Find handler Main() Main() .NET CLR 9. Find handler 1. Execute the program 10. Display error message

80 Using throw Keyword Throwing an exception with error message:
* Using throw Keyword Throwing an exception with error message: Exceptions can take message and cause: Note: if the original exception is not passed the initial cause of the exception is lost throw new ArgumentException("Invalid amount!"); try { Int32.Parse(str); } catch (FormatException fe) throw new ArgumentException("Invalid number", fe); (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

81 Throwing Exceptions – Example
* Throwing Exceptions – Example public static double Sqrt(double value) { if (value < 0) throw new System.ArgumentOutOfRangeException( "Sqrt for negative numbers is undefined!"); return Math.Sqrt(value); } static void Main() try Sqrt(-1); catch (ArgumentOutOfRangeException ex) Console.Error.WriteLine("Error: " + ex.Message); throw; (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

82 Strings and Text Processing
* Strings and Text Processing (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

83 What Is String? Strings are sequences of characters
Each character is a Unicode symbol Represented by the string data type in C# (System.String) Example: string s = "Hello, C#"; s H e l o , C #

84 The System.String Class
Strings are represented by System.String objects in .NET Framework String objects contain an immutable (read-only) sequence of characters Strings use Unicode in to support multiple languages and alphabets Strings are stored in the dynamic memory (managed heap) System.String is reference type

85 The System.String Class (2)
String objects are like arrays of characters (char[]) Have fixed length (String.Length) Elements can be accessed directly by index The index is in the range [0...Length-1] string s = "Hello!"; int len = s.Length; // len = 6 char ch = s[1]; // ch = 'e' index = 1 2 3 4 5 H e l o ! s[index] =

86 Strings – Example static void Main() { string s =
"Stand up, stand up, Balkan Superman."; Console.WriteLine("s = \"{0}\"", s); Console.WriteLine("s.Length = {0}", s.Length); for (int i = 0; i < s.Length; i++) Console.WriteLine("s[{0}] = {1}", i, s[i]); }

87 Reading and Printing Strings
Reading strings from the console Use the method Console.ReadLine() string s = Console.ReadLine(); Printing strings to the console Use the methods Write() and WriteLine() Console.Write("Please enter your name: "); string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name); Console.WriteLine("Welcome to our party!");

88 Comparing Strings A number of ways exist to compare two strings:
Dictionary-based string comparison Case-insensitive Case-sensitive int result = string.Compare(str1, str2, true); // result == 0 if str1 equals str2 // result < 0 if str1 if before str2 // result > 0 if str1 if after str2 string.Compare(str1, str2, false);

89 Comparing Strings – Example
Finding the first string in a lexicographical order from a given list of strings: string[] towns = {"Sofia", "Varna", "Plovdiv", "Pleven", "Bourgas", "Rousse", "Yambol"}; string firstTown = towns[0]; for (int i=1; i<towns.Length; i++) { string currentTown = towns[i]; if (String.Compare(currentTown, firstTown) < 0) firstTown = currentTown; } Console.WriteLine("First town: {0}", firstTown);

90 Concatenating Strings
There are two ways to combine strings: Using the Concat() method Using the + or the += operators Any object can be appended to string string str = String.Concat(str1, str2); string str = str1 + str2 + str3; string str += str1; string name = "Peter"; int age = 22; string s = name + " " + age; //  "Peter 22"

91 Searching in Strings Finding a character or substring within given string First occurrence First occurrence starting at given position Last occurrence IndexOf(string str) IndexOf(string str, int startIndex) LastIndexOf(string)

92 Searching in Strings – Example
string str = "C# Programming Course"; int index = str.IndexOf("C#"); // index = 0 index = str.IndexOf("Course"); // index = 15 index = str.IndexOf("COURSE"); // index = -1 // IndexOf is case-sensetive. -1 means not found index = str.IndexOf("ram"); // index = 7 index = str.IndexOf("r"); // index = 4 index = str.IndexOf("r", 5); // index = 7 index = str.IndexOf("r", 8); // index = 18 index = 1 2 3 4 5 6 7 8 9 10 11 12 13 C # P r o g a m i n s[index] =

93 Extracting Substrings
str.Substring(int startIndex, int length) str.Substring(int startIndex) string filename string name = filename.Substring(8, 8); // name is Rila2009 string filename string nameAndExtension = filename.Substring(8); // nameAndExtension is Summer2009.jpg 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 C : \ P i c s R l a . j p g

94 Splitting Strings To split a string by given separator(s) use the following method: Example: string[] Split(params char[]) string listOfBeers = "Amstel, Zagorka, Tuborg, Becks."; string[] beers = listOfBeers.Split(' ', ',', '.'); Console.WriteLine("Available beers are:"); foreach (string beer in beers) { Console.WriteLine(beer); }

95 Replacing and Deleting Substrings
Replace(string, string) – replaces all occurrences of given string with another The result is new string (strings are immutable) Remove(index, length) – deletes part of a string and produces new string as result string cocktail = "Vodka + Martini + Cherry"; string replaced = cocktail.Replace("+", "and"); // Vodka and Martini and Cherry string price = "$ "; string lowPrice = price.Remove(2, 3); // $ 4567

96 Changing Character Casing
Using method ToLower() Using method ToUpper() string alpha = "aBcDeFg"; string lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha); string alpha = "aBcDeFg"; string upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha);

97 Trimming White Space Using method Trim() Using method Trim(chars)
Using TrimStart() and TrimEnd() string s = " example of white space "; string clean = s.Trim(); Console.WriteLine(clean); string s = " \t\nHello!!! \n"; string clean = s.Trim(' ', ',' ,'!', '\n','\t'); Console.WriteLine(clean); // Hello string s = " C# "; string clean = s.TrimStart(); // clean = "C# "

98 Constructing Strings Strings are immutable
Concat(), Replace(), Trim(), ... return new string, do not modify the old one

99 Changing the Contents of a String – StringBuilder
* Changing the Contents of a String – StringBuilder Use the System.Text.StringBuilder class for modifiable strings of characters: Use StringBuilder if you need to keep adding characters to a string public static string ReverseString(string s) { StringBuilder sb = new StringBuilder(); for (int i = s.Length-1; i >= 0; i--) sb.Append(s[i]); return sb.ToString(); } Introducing the StringBuffer Class StringBuffer represents strings that can be modified and extended at run time. The following example creates three new String objects, and copies all the characters each time a new String is created: String quote = "Fasten your seatbelts, "; quote = quote + "it’s going to be a bumpy night."; It is more efficient to preallocate the amount of space required using the StringBuffer constructor, and its append() method as follows: StringBuffer quote = new StringBuffer(60); // alloc 60 chars quote.append("Fasten your seatbelts, "); quote.append(" it’s going to be a bumpy night. "); StringBuffer also provides a number of overloaded insert() methods for inserting various types of data at a particular location in the string buffer. Instructor Note The example in the slide uses StringBuffer to reverse the characters in a string. A StringBuffer object is created, with the same length as the string. The loop traverses the String parameter in reverse order and appends each of its characters to the StringBuffer object by using append(). The StringBuffer therefore holds a reverse copy of the String parameter. At the end of the method, a new String object is created from the StringBuffer object, and this String is returned from the method. (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

100 The StringBuilder Class
Capacity StringBuilder: Length=9 Capacity=15 H e l o , C # ! used buffer (Length) unused buffer StringBuilder keeps a buffer memory, allocated in advance Most operations use the buffer memory and do not allocate new objects

101 StringBuilder – Example
Extracting all capital letters from a string public static string ExtractCapitals(string s) { StringBuilder result = new StringBuilder(); for (int i = 0; i<s.Length; i++) if (Char.IsUpper(s[i])) result.Append(s[i]); } return result.ToString();

102 Method ToString() All classes have public virtual method ToString()
Returns a human-readable, culture-sensitive string representing the object Most .NET Framework types have own implementation of ToString() int, float, bool, DateTime int number = 5; string s = "The number is " + number.ToString(); Console.WriteLine(s); // The number is 5

103 Method ToString(format)
We can apply specific formatting when converting objects to string ToString(formatString) method int number = 42; string s = number.ToString("D5"); // 00042 s = number.ToString("X"); // 2A double d = 0.375; s = d.ToString("P2"); // %

104 Formatting Strings The formatting strings are different for the different types Some formatting strings for numbers: D – number (for integer types) C – currency (according to current culture) E – number in exponential notation P – percentage X – hexadecimal number F – fixed point (for real numbers)

105 Method String.Format()
Applies templates for formatting strings Placeholders are used for dynamic text Like Console.WriteLine(…) string template = "If I were {0}, I would {1}."; string sentence1 = String.Format( template, "developer", "know C#"); Console.WriteLine(sentence1); // If I were developer, I would know C#. string sentence2 = String.Format( template, "elephant", "weigh 4500 kg"); Console.WriteLine(sentence2); // If I were elephant, I would weigh 4500 kg.

106 Composite Formatting The placeholders in the composite formatting strings are specified as follows: Examples: {index[,alignment][:formatString]} double d = 0.375; s = String.Format("{0,10:F5}", d); // s = " 0,37500" int number = 42; Console.WriteLine("Dec {0:D} = Hex {1:X}", number, number); // Dec 42 = Hex 2A

107 Formatting Dates Dates have their own formatting strings
d, dd – day (with/without leading zero) M, MM – month yy, yyyy – year (2 or 4 digits) h, HH, m, mm, s, ss – hour, minute, second DateTime now = DateTime.Now; Console.WriteLine( "Now is {0:d.MM.yyyy HH:mm:ss}", now); // Now is :30:32

108 C# Language ? ? ? ? ? Questions? ? ? ? ? ?


Download ppt "C# Language."

Similar presentations


Ads by Google