Sei sulla pagina 1di 33

hi

assembly manifest - An integral part of every assembly that renders the assembly self-describing. The
assembly manifest contains the assembly's metadata. The manifest establishes the assembly identity,
specifies the files that make up the assembly implementation, specifies the types and resources that make
up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of
permissions required for the assembly to run properly. This information is used at run time to resolve
references, enforce version binding policy, and validate the integrity of loaded assemblies. The selfdescribing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible.
metadata - Information that describes every element managed by the common language runtime: an
assembly, loadable file, type, method, and so on. This can include information required for debugging and
garbage collection, as well as security attributes, marshaling data, extended class and member definitions,
version binding, and other information required by the runtime.

dipa ahuja replied to sri on 15-May-11 07:34 AM

Assembly metadata is stored in Manifest. Manifest contains all the metadata


needed to do :Version of assembly, Security identity, Scope of the assembly
Resolve references to resources and classes.
The assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate languages (MSIL) code or in stand-alone PE file that
contains only assembly manifest information.
Jitendra Faye replied to sri on 15-May-11 10:47 AM
menifest also reffered to as assembly metadata(data about data),contains all information related to
assembly like identity section,version number,strong name (optional),culture.so menifest contains
infomation related to the identification assembly or it is a part of assembly where assembly is self
describing.
metadata is the information that enables components to be self describing.it is used to describe which
class is used,funtion,methods,fields ....So it is the data about data.
Manifest is part of MetaData.
Manifest contains information about Assembly version culture dependencies etc.
while Metadata is data about data i.e. information about classes in the assembly various datatypes etc.
Riley K replied to sri on 16-May-11 12:12 AM

In simple words, assembly manifest contains the assembly metadata. An


assembly manifest contains all the metadata needed to specify the
assembly's version requirements and security identity, and all metadata
needed to define the scope of the assembly and

resolve references to resources and classes. To understand Metadata,


you can refer to:
http://en.wikipedia.org/wiki/.NET_metadata
And here is the introduction to Manifest in MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/enus/cpguide/html/cpconAssemblyManifest.asp

Manifest Maintains the information about the assemblies


like version, name locale and an optional strong name that
uniquely identifying the assembly. This manifest
information is used by the CLR. The manifest also contains
the security demands to verify this assembly. It also
contains the names and hashes of all the files that make up
the assembly. The .NET assembly manifest contains a
cryptographic hash of different modules in the assembly.
And when the assembly is loaded, the CLR recalculates the
hash of the modules at hand, and compares it with the
embeded hash. If the hash generated at runtime is different
from that found in the manifest, .NET refuses to load the
assembly and throws an exception.
Metadata means Data about the data.metadata yields the
types available in that assembly, viz. classes, interfaces,
enums, structs, etc., and their containing namespaces, the
name of each type, its visibility/scope, its base class,
the interfaces it implemented, its methods and their scope,
and each methods parameters, types properties, and so on.
The assembly metada is generated by the high-level
compilers automatically from the source files. The compiler
embeds the metadata in the target output file, a dll,

an .exe or a .netmodule in the case of multi-module


assembly.

Why do some people use the Finalize method over the Dispose method
The finalizer method is called when your object is garbage collected and you have no guarantee
when this will happen (you can force it, but it will hurt performance).
The Dispose method on the other hand is meant to be called by the code that created your class so
that you can clean up and release any resources you have acquired (unmanaged data, database
connections, file handles, etc) the moment the code is done with your object.
The standard practice is to implement IDisposable and Dispose so that you can use your object in
a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you
call Dispose, just in case the calling code forgot to dispose of you.
share

Finalize

Finalizers should always be protected, not public or private so that the method cannot be called
from the application's code directly and at the same time, it can make a call to the base.Finalize
method
Finalizers should release unmanaged resources only.
The framework does not guarantee that a finalizer will execute at all on any given instance.
Never allocate memory in finalizers or call virtual methods from finalizers.
Avoid synchronization and raising unhandled exceptions in the finalizers.
The execution order of finalizers is non-deterministicin other words, you can't rely on another
object still being available within your finalizer.
Do not define finalizers on value types.
Don't create empty destructors. In other words, you should never explicitly define a destructor
unless your class needs to clean up unmanaged resourcesand if you do define one, it should
do some work. If, later, you no longer need to clean up unmanaged resources in the destructor,
remove it altogether.
Dispose

Implement IDisposable on every type that has a finalizer


Ensure that an object is made unusable after making a call to the Dispose method. In other
words, avoid using an object after the Dispose method has been called on it.
Call Dispose on all IDisposable types once you are done with them
Allow Dispose to be called multiple times without raising errors.
Suppress later calls to the finalizer from within the Dispose method using the
GC.SuppressFinalize method
Avoid creating disposable value types
Avoid throwing exceptions from within Dispose methods
Dispose/Finalized Pattern

Microsoft recommends that you implement both Dispose and Finalize when working with
unmanaged resources. The Finalize implementation would run and the resources would still be
released when the object is garbage collected even if a developer neglected to call the Dispose
method explicitly.

Cleanup the unmanaged resources in the Finalize method as well as Dispose method.
Additionally call the Dispose method for any .NET objects that you have as components inside
that class(having unmanaged resources as their member) from the Dispose() method.

There are two types of assemblies are there in .net. They are,
1. Private Assemblies and
2. Public/Shared Assemblies.
Private Assembly:- An assembly is used only for a particular application. It is stored in the
application's directory other wise in the application's sub directory. There is no version
constraint in private assembly.
Public Assembly:- It has version constraint. This public assembly is stored inside the global
assembly cache or GAC.GAC contains a collection of shared assemblies.

Assembly Versioning
.NET Framework 4.5
Other Versions

2 out of 3 rated this helpful - Rate this topic


All versioning of assemblies that use the common language runtime is done at the assembly level. The
specific version of an assembly and the versions of dependent assemblies are recorded in the assembly's
manifest. The default version policy for the runtime is that applications run only with the versions they
were built and tested with, unless overridden by explicit version policy in configuration files (the
application configuration file, the publisher policy file, and the computer's administrator configuration
file).

Note

Versioning is done only on assemblies with strong names.


The runtime performs several steps to resolve an assembly binding request:
1. Checks the original assembly reference to determine the version of the assembly to be bound.
2. Checks for all applicable configuration files to apply version policy.
3. Determines the correct assembly from the original assembly reference and any redirection
specified in the configuration files, and determines the version that should be bound to the
calling assembly.

4.

Checks the global assembly cache, codebases specified in configuration files, and then checks the
application's directory and subdirectories using the probing rules explained in How the Runtime
Locates Assemblies.
The following illustration shows these steps.
Resolving an assembly binding request

For more information about configuring applications, see Configuration Files. For more information about
binding policy, seeHow the Runtime Locates Assemblies.

Version Information
Each assembly has two distinct ways of expressing version information:
The assembly's version number, which, together with the assembly name and culture information,
is part of the assembly's identity. This number is used by the runtime to enforce version policy
and plays a key part in the type resolution process at run time.
An informational version, which is a string that represents additional version information included
for informational purposes only.

Assembly Version Number


Each assembly has a version number as part of its identity. As such, two assemblies that differ by version
number are considered by the runtime to be completely different assemblies. This version number is
physically represented as a four-part string with the following format:
<major version>.<minor version>.<build number>.<revision>
For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version, 1254 as the build
number, and 0 as the revision number.

The version number is stored in the assembly manifest along with other identity information, including the
assembly name and public key, as well as information on relationships and identities of other assemblies
connected with the application.
When an assembly is built, the development tool records dependency information for each assembly that
is referenced in the assembly manifest. The runtime uses these version numbers, in conjunction with
configuration information set by an administrator, an application, or a publisher, to load the proper
version of a referenced assembly.
The runtime distinguishes between regular and strong-named assemblies for the purposes of versioning.
Version checking only occurs with strong-named assemblies.
For information about specifying version binding policies, see Configuration Files. For information about
how the runtime uses version information to find a particular assembly, see How the Runtime Locates
Assemblies.

Assembly Informational Version


The informational version is a string that attaches additional version information to an assembly for
informational purposes only; this information is not used at run time. The text-based informational version
corresponds to the product's marketing literature, packaging, or product name and is not used by the
runtime. For example, an informational version could be "Common Language Runtime version 1.0" or
"NET Control SP 2". On the Version tab of the file properties dialog in Microsoft Windows, this information
appears in the item "Product Version".

Note

Although you can specify any text, a warning message appears on compilation if the string is not in the
format used by the assembly version number, or if it is in that format but contains wildcards. This
warning is harmless.

How to use Assembly Version and Assembly File Version


.NET framework provides opportunity to set two different types of version numbers to each assembly.
Assembly Version : This is the version number used by framework during build and at runtime to locate,
link and load the assemblies. When you add reference to any assembly in your project, it is this version
number which gets embedded. At runtime, CLR looks for assembly with this version number to load. But
remember this version is used along with name, public key token and culture information only if the
assemblies are strong-named signed. If assemblies are not strong-named signed, only file names are used
for loading.
Assembly File Version : This is the version number given to file as in file system. It is displayed by
Windows Explorer. Its never used by .NET framework or runtime for referencing.
Attributes in AssemblyInfo.cs
// Version information for an assembly consists of the following four values:
//

//

Major Version

//

Minor Version

//

Build Number

//

Revision

//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Providing a (*) in place of absolute number makes compiler increase the number by one every time you
build.
Suppose you are building a framework assembly for your project which is used by lot of developers while
building the application assemblies. If you release new version of assembly very frequently, say once every
day, and if assemblies are strong named, Developers will have to change the reference every time you
release new assembly. This can be quite cumbersome and may lead to wrong references also. A better
option in such closed group and volatile scenarios would be to fix he 'Assembly Version' and change
only the 'Assembly File Version'. Use the assembly file version number to communicate the latest release
of assembly. In this case, developers will not have to change the references and they can simply overwrite
the assembly in reference path. In central/final release builds it makes more sense to change the
'Assembly Version' and most keep the 'Assembly File Version' same as assembly version.

C# String Functions and Properties


OBJECTIVE
In this chapter you will learn:
W hat is string?
How many types of string f uncti on i n C#?
How t o use C# string function i n pr ogramming?
W hat is the differ enc e between string and String?

In C# programming, string is another kind of data type that represents Unicode


Characters. It is the alias of System.String however, you can also write System.String
instead of string. It is the sequence of character in which each character is a Unicode
character.
There is no difference between s tring and String because string is the alias of
System.String. Most of the developers get confused what to use between sting and String.
Technically there is no difference between them and they can use any of them. However,
you will have to use using System to use the String in C#. Another difference is String is
a class name whereas string is a reserved keyword. You should always use string instead
of String.

C# string function

String Functions

Definitions

Clone()

Make clone of string.

CompareTo()

Compare two strings and returns integer value as output. It returns 0


for true and 1 for false.

Contains()

The C# Contains method checks whether specified character or string is


exists or not in the string value.

EndsWith()

This EndsWith Method checks whether specified character is the last


character of string or not.

Equals()

The Equals Method in C# compares two string and returns Boolean


value as output.

GetHashCode()

This method returns HashValue of specified string.

GetType()

It returns the System.Type of current instance.

GetTypeCode()

It returns the Stystem.TypeCode for class System.String.

IndexOf()

Returns the index position of first occurrence of specified character.

ToLower()

Converts String into lower case based on rules of the current culture.

ToUpper()

Converts String into Upper case based on rules of the current culture.

Insert()

Insert the string or character in the string at the specified position.

IsNormalized()

This method checks whether this string is in Unicode normalization


form C.

LastIndexOf()

Returns the index position of last occurrence of specified character.

Length

It is a string property that returns length of string.

Remove()

This method deletes all the characters from beginning to specified index
position.

Replace()

This method replaces the character.

Split()

This method splits the string based on specified value.

StartsWith()

It checks whether the first character of string is same as specified


character.

Substring()

This method returns substring.

ToCharArray()

Converts string into char array.

Trim()

It removes extra whitespaces from beginning and ending of string.

Programming Examples of C# String Function:


using System.Text;
namespace string_function
{
class Program
{
static void Main(string[]

args)
{

string firstname;
string lastname;

firstname

= "Steven

Clark";

lastname

= "Clark";

Console.WriteLine(firstname.Clone());
//

Make

String

Clone

Console.WriteLine(firstname.CompareTo(lastname));
//Compare
two
1 for false

string

value

and

returns

for

true

Console.WriteLine(firstname.Contains( "ven")); //Check


specified value exists or not in string

whether

Console.WriteLine(firstname.EndsWith( "n")); //Check


specified

value

is

the

last

character

and

whether
of

string

Console.WriteLine(firstname.Equals(lastname));
//Compare two string and returns true and false

Console.WriteLine(firstname.GetHashCode());
//Returns HashCode of String

Console.WriteLine(firstname.GetType());
//Returns type of string
Console.WriteLine(firstname.GetTypeCode());
//Returns type of string
Console.WriteLine(firstname.IndexOf("e"));//Returns the first index
position
of
specified
the first index position of specified value

value

Console.WriteLine(firstname.ToLower());
//Covert string into lower case
Console.WriteLine(firstname.ToUpper());
//Convert string into Upper case
Console.WriteLine(firstname.Insert(0, "Hello"));//Insert
into string

substring

Console.WriteLine(firstname.IsNormalized());
//Check
from C

Whether

string

is

in

Unicode

normalization

Console.WriteLine(firstname.LastIndexOf( "e"));//Returns
index position of specified value

the

last

Console.WriteLine(firstname.Length);
//Returns the Length of String
Console.WriteLine(firstname.Remove(5));
//Deletes all the characters from begining to specified index.
Console.WriteLine(firstname.Replace('e','i')); //

Replace

the

character
string[] split = firstname.Split(new char[]
string based on specified value

{ 'e'}); //Split

the

Console.WriteLine(split[0]);
Console.WriteLine(split[1]);
Console.WriteLine(split[2]);
Console.WriteLine(firstname.StartsWith( "S"));//Check
character of string is same as specified value

wheter

first

Console.WriteLine(firstname.Substring(2,5));
//Returns substring
Console.WriteLine(firstname.ToCharArray());
//Converts an string into char array.
Console.WriteLine(firstname.Trim());
//It

removes

starting

and

ending

white

spaces

from

string.
}
}
}

Output

Steven Clark
1
True
False
False
1470518261
System.String
String
2
steven clark
STEVEN CLARK
HelloSteven Clark
True
4
12
Steve
Stivin Clark
St
v
n Clark
True
even
Steven Clark
Steven Clark

Strings in C#

In this part of the C# tutorial, we will work with string data in more detail. Strings are
very important in computer languages. That is why we dedicate a whole chapter to
working with strings in C#.
A string is a sequence of characters. In C#, a string is a sequence of unicode characters.
It is a data type which stores a sequence of data values, usually bytes, in which elements
usually stand for characters according to a character encoding. When a string appears
literally in the source code, it is known as a string literal.
Strings are objects. There are two basic classes for working with strings:

System.String

System.Text.StringBuilder

The String is an immutable sequence of characters. The StringBuilder is a mutable


sequence of characters.
In C#, string is an alias for System.String. The string is a language keyword and
theSystem.String is a .NET type.

Initializing strings
There are multiple ways of creating strings, both immutable and mutable. We will show
a few of them.
using System;
using System.Text;
public class Initialization
{
static void Main()
{
char[] cdb = {'M', 'y', 'S', 'q', 'l'};
string lang = "C#";
String ide = "NetBeans";
string db = new string(cdb);
Console.WriteLine(lang);
Console.WriteLine(ide);
Console.WriteLine(db);
StringBuilder sb1 = new StringBuilder(lang);
StringBuilder sb2 = new StringBuilder();
sb2.Append("Fields");
sb2.Append(" of ");

sb2.Append("glory");
Console.WriteLine(sb1);
Console.WriteLine(sb2);
}
}

The example shows a few ways of


creating System.String and System.Text.StringBuilderobjects.
using System.Text;

This statement enables to use the System.Text.StringBuilder type without


qualification.
string lang = "C#";
String ide = "NetBeans";

The most common way is to create a string object from a string literal.
string db = new string(cdb);

Here we create a string object from an array of characters. The string is an alias for
theSystem.String.
StringBuilder sb1 = new StringBuilder(lang);

A StringBuilder object is created from a String.


StringBuilder sb2 = new StringBuilder();
sb2.Append("Fields");
sb2.Append(" of ");
sb2.Append("glory");

We create an empty StringBuilder object. We append three strings into the object.
$ ./initialization.exe
C#
NetBeans
MySql
C#
Fields of glory

Running the example gives this result.

Strings are objects


Strings are objects. They are reference types. Strings are instances of
the System.String orSystem.Text.StringBuilder class. Since they are objects, they have
multiple methods available for doing various work.
using System;
public class CSharpApp
{
static void Main()
{
string lang = "Java";
string bclass = lang.GetType().Name;
Console.WriteLine(bclass);
string parclass = lang.GetType().BaseType.Name;
Console.WriteLine(parclass);
if (lang.Equals(String.Empty))
{
Console.WriteLine("The string is empty");
} else
{
Console.WriteLine("The string is not empty");
}
int l = lang.Length;
Console.WriteLine("The string has " + l + " characters");
}
}

In this program, we demonstrate that strings are objects. Objects must have a class
name, a parent class and they must also have some methods that we can call or
properties to access.
string lang = "Java";

An object of System.String type is created.


string bclass = lang.GetType().Name;
Console.WriteLine(bclass);

We determine the class name of the object to which the lang variable refers.
string parclass = lang.GetType().BaseType.Name;
Console.WriteLine(parclass);

A parent class of our object is received. All objects have at least one parent the Object.
if (lang.Equals(String.Empty))
{
Console.WriteLine("The string is empty");
} else
{
Console.WriteLine("The string is not empty");
}

Objects have various methods. With the Equals() method we check if the string is
empty.
int l = lang.Length;

The Length method returns the size of the string.


$ ./stringobjects.exe
String
Object
The string is not empty
The string has 4 characters

This is the output of the stringobjects.exe program.

Mutable & immutable strings


The String is a sequence of immutable characters, while the StringBuilder is a
sequence of mutable characters. The next example will show the difference.
using System;
using System.Text;
public class CSharpApp
{
static void Main()
{
string name = "Jane";
string name2 = name.Replace('J', 'K');
string name3 = name2.Replace('n', 't');
Console.WriteLine(name);
Console.WriteLine(name3);
StringBuilder sb = new StringBuilder("Jane");
Console.WriteLine(sb);
sb.Replace('J', 'K', 0, 1);

sb.Replace('n', 't', 2, 1);


Console.WriteLine(sb);
}
}

Both objects have methods for replacing characters in a string.


string name = "Jane";
string name2 = name.Replace('J', 'K');
string name3 = name2.Replace('n', 't');

Calling a Replace() method on a String results in returning a new modified string. The
original string is not changed.
sb.Replace('J', 'K', 0, 1);
sb.Replace('n', 't', 2, 1);

The Replace() method of a StringBuilder will replace a character at the given index
with a new character. The original string is modified.
$ ./mutableimmutable.exe
Jane
Kate
Jane
Kate

This is the output of the mutableimmutable.exe program.

Concatenating strings
Immutable strings can be added using the + operator or the Concat() method. They will
form a new string which is a chain of all concatenated strings. Mutable strings have
the Append() method which builds a string from any number of other strings.
using System;
using System.Text;
public class Concatenate
{
static void Main()
{
Console.WriteLine("Return" + " of " + "the king.");
Console.WriteLine(string.Concat(string.Concat("Return", " of "),

"the king."));
StringBuilder sb = new StringBuilder();
sb.Append("Return");
sb.Append(" of ");
sb.Append("the king.");
Console.WriteLine(sb);
}
}

The example creates three sentences by adding strings.


Console.WriteLine("Return" + " of " + "the king.");

A new string is formed by using the + operator.


Console.WriteLine(string.Concat(string.Concat("Return", " of "),
"the king."));

The Concat() method concatenates two strings. The method is a static method of
theSystem.String class.
StringBuilder sb = new StringBuilder();
sb.Append("Return");
sb.Append(" of ");
sb.Append("the king.");

A mutable object of the StringBuilder type is created by calling the Append() method
three times.
$ ./concatenate.exe
Return of the king.
Return of the king.
Return of the king.

This is the example output.

Using quotes
What if we wanted to display quotes, for example in a direct speech? In such a case,
inner quotes must be escaped.
using System;

public class Quotes


{
static void Main()
{
Console.WriteLine("There are many stars.");
Console.WriteLine("He said, \"Which one is your favourite?\"");
}
}

We use the (\) character to escape additional quotes.


$ ./quotes.exe
There are many stars.
He said, "Which one is your favourite?"

This is the output of the quotes.exe program.

Multiline strings
It is possible to create a multiline string in C#.
using System;
public class Multiline
{
static void Main()
{
string multiString = @"I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good";
Console.WriteLine(multiString);
}
}

A multiline string can be created easily by using the @ character at the beginning of the
string.
$ ./multiline.exe
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good

Comparing strings
We can compare two strings with the == operator.
using System;
public class CSharpApp
{
static void Main()
{
Console.WriteLine("12" == "12");
Console.WriteLine("17" == "9");
Console.WriteLine("aa" == "ab");
}
}

In the example program, we compare strings.


$ ./compare.exe
True
False
False

This is the output of the program.


There is a string.Compare() method, which compares two specified strings and returns
an integer that indicates their relative position in the sort order. If the returned value is
less than zero, the first string is less than the second. If it returns zero, both strings are
equal. Finally, if the returned value is greater than zero, the first string is greater than
the second.
using System;
public class CSharpApp
{
static void Main()
{
string str1 = "ZetCode";
string str2 = "zetcode";
Console.WriteLine(string.Compare(str1, str2, true));
Console.WriteLine(string.Compare(str1, str2, false));
}
}

There is an optional third ignoreCase argument. It determines if the case should be


honored or not.
Console.WriteLine(string.Compare(str1, str2, true));

Compare two strings and ignore the case. This line prints 0 to the console.

String elements
A string is a sequence of characters. A character is a basic element of a string.
using System;
public class Elements
{
static void Main()
{
char[] crs = {'Z', 'e', 't', 'C', 'o', 'd', 'e' };
String s = new String(crs);
char c1 = s[0];
char c2 = s[(s.Length-1)];
Console.WriteLine(c1);
Console.WriteLine(c2);
int i1 = s.IndexOf('e');
int i2 = s.LastIndexOf('e');
Console.WriteLine("The first index of character e is " + i1);
Console.WriteLine("The last index of character e is " + i2);
Console.WriteLine(s.Contains("t"));
Console.WriteLine(s.Contains("f"));
char[] elements = s.ToCharArray();
foreach (char el in elements)
{
Console.WriteLine(el);
}
}
}

In the first example, we will work with an immutable string.


char[] crs = {'Z', 'e', 't', 'C', 'o', 'd', 'e' };
String s = new String(crs);

A new immutable string is formed from an array of characters.

char c1 = s[0];
char c2 = s[(s.Length-1)];

Using the array access notation, we we get the first and the last char value of the string.
int i1 = s.IndexOf('e');
int i2 = s.LastIndexOf('e');

With the above methods, we get the first and the last occurence of the character 'e'.
Console.WriteLine(s.Contains("t"));
Console.WriteLine(s.Contains("f"));

With the Contains() method we check if the string contains the 't' character. The
method returns a boolean value.
char[] elements = s.ToCharArray();
foreach (char el in elements)
{
Console.WriteLine(el);
}

The ToCharArray() method creates a character array from the string. We go through the
array and print each of the characters.
$ ./stringelemetns.exe
Z
e
The first index of character e is 1
The last index of character e is 6
True
False
Z
e
t
C
o
d
e

This is the example output.


In the second example, we will work with the elements of a mutable string.

using System;
using System.Text;
public class StringBuilderElements
{
static void Main()
{
StringBuilder sb = new StringBuilder("Misty mountains");
Console.WriteLine(sb);
sb.Remove(sb.Length-1, 1);
Console.WriteLine(sb);
sb.Append('s');
Console.WriteLine(sb);
sb.Insert(0, 'T');
sb.Insert(1, 'h');
sb.Insert(2, 'e');
sb.Insert(3, ' ');
Console.WriteLine(sb);
sb.Replace('M', 'm', 4, 1);
Console.WriteLine(sb);
}
}

A mutable string is formed. We modify the contents of the string by deleting, appending,
inserting and replacing characters.
sb.Remove(sb.Length-1, 1);

This line deletes the last character.


sb.Append('s');

The deleted character is appended back to the string.


sb.Insert(0,
sb.Insert(1,
sb.Insert(2,
sb.Insert(3,

'T');
'h');
'e');
' ');

We insert four characters at the beginning of the string.


sb.Replace('M', 'm', 4, 1);

Finally, we replace a character at index 4.


$ ./stringbuilderelements.exe
Misty mountains

Misty mountain
Misty mountains
The Misty mountains
The misty mountains

From the output we can see how the mutable string is changing.

String methods
C# has useful built-in methods that can be used for working with strings.
The Join() and Split() are very handy methods.
using System;
public class JoinSplit
{
static void Main()
{
string[] items = new string[] {"C#", "Visual Basic",
"Java", "Perl"};
string langs = string.Join(",", items);
Console.WriteLine(langs);
string[] ls = langs.Split(',');
foreach (string lang in ls)
{
Console.WriteLine(lang);
}
}
}

In our program, we will join and split strings.


string[] items = new string[] {"C#", "Visual Basic",
"Java", "Perl"};

This is an array of strings. These strings are going to be joined.


string langs = string.Join(",", items);

All words from the array are joined. We build one string from them. There will be a
comma character between each two words.
string[] ls = langs.Split(',');

As a reverse operation, we split the langs string. The Split() method returns an array of
words, delimited by a character. In our case it is a comma character.
foreach (string lang in ls)
{
Console.WriteLine(lang);
}

We go through the array and print its elements.


$ ./joinsplit.exe
C#,Visual Basic,Java,Perl
C#
Visual Basic
Java
Perl

This is the output of the example.


using System;
public class StringMethods
{
static void Main()
{
string str = "Determination";
Console.WriteLine(str.Contains("e"));
Console.WriteLine(str.IndexOf("e"));
Console.WriteLine(str.LastIndexOf("i"));
Console.WriteLine(str.ToUpper());
Console.WriteLine(str.ToLower());
}
}

We introduce five string methods in the above example.


Console.WriteLine(str.Contains("e"));

The Contains() method returns True if the string contains a specific character.
Console.WriteLine(str.IndexOf("e"));

The IndexOf() returns the first index of a letter in the string.


Console.WriteLine(str.LastIndexOf("i"));

The LastIndexOf() methods returns the last index of a letter in a string.


Console.WriteLine(str.ToUpper());
Console.WriteLine(str.ToLower());

Letters of the string are converted to uppercase with the ToUpper() method and to
lowercase with the ToLower() method.
$ ./strmethods.exe
True
1
10
DETERMINATION
determination

Running the program.

Copy vs Clone
We will describe a difference between two methods: Copy() and Clone().
The Copy() method creates a new instance of string with the same value as a specified
string. The Clone() method returns a reference to the string which is being cloned. It is
not an independent copy of the string on the Heap. It is another reference on the same
string.
using System;
public class CopyClone
{
static void Main()
{
string str = "ZetCode";
string cloned = (string) str.Clone();
string copied = string.Copy(str);
Console.WriteLine(str.Equals(cloned)); // prints true
Console.WriteLine(str.Equals(copied)); // prints true
Console.WriteLine(ReferenceEquals(str, cloned)); // prints true
Console.WriteLine(ReferenceEquals(str, copied)); // prints false
}
}

Our example demonstrates the difference between the two methods.

string cloned = (string) str.Clone();


string copied = string.Copy(str);

The string value is cloned and copied.


Console.WriteLine(str.Equals(cloned)); // prints true
Console.WriteLine(str.Equals(copied)); // prints true

The Equals() method determines whether two string objects have the same value. The
contents of all three strings are the same.
Console.WriteLine(ReferenceEquals(str, cloned)); // prints true
Console.WriteLine(ReferenceEquals(str, copied)); // prints false

The ReferenceEquals() method compares the two reference objects. Therefore


comparing a copied string to the original string returns false. Because they are two
distinct objects.

Formatting strings
In the next examples, we will format strings. The .NET Framework has a feature
calledcomposite formatting. It is supported by Format() and WriteLine() methods. A
method takes a list of objects and a composite format string as input. The format string
consists of fixed string and some format items. These format items are indexed
placeholders which correspond to the objects in the list.
The format item has the following syntax:
{index[,length][:formatString]}

The index component is mandatory. It is a number starting from 0 that refers to an item
from the list of objects. Multiple items can refer to the same element of the list of
objects. An object is ignored if it is not referenced by a format item. If we refer outside
the bounds of the list of objects, a runtime exception is thrown.
The length component is optional. It is the minimum number of characters in the string
representation of the parameter. If positive, the parameter is right-aligned; if negative, it
is left-aligned. If it is specified, there must by a colon separating the index and the
length.

The formatString is optional. It is a string that formats a value is a specific way. It can be
used to format dates, times, numbers or enumerations.
Here we show, how to work with length component of the format items. We print three
columns of numbers to the terminal. Left, middle and right aligned.
using System;
public class Format1
{
static void Main()
{
int oranges = 2;
int apples = 4;
int bananas = 3;
string str1 = "There are {0} oranges, {1} apples and " +
"{2} bananas";
string str2 = "There are {1} oranges, {2} bananas and " +
"{0} apples";
Console.WriteLine(str1, oranges, apples, bananas);
Console.WriteLine(str2, apples, oranges, bananas);
}
}

We print a simple message to the console. We use only index component of the format
item.
string str1 = "There are {0} oranges, {1} apples and " +
"{2} bananas";

The {0}, {1}, and {2} are format items. We specify the index component. Other
components are optional.
Console.WriteLine(str1, oranges, apples, bananas);

Now we put together the composite formatting. We have the string and the list of objects
(oranges, apples, bananas). The {0} format item refers to the oranges.
The WriteLine() method replaces the {0} format item with the contents of the oranges
variable.
string str2 = "There are {1} oranges, {2} bananas and " +
"{0} apples";

The order of the format items referring to the objects is notation important.

$ ./format1.exe
There are 2 oranges, 4 apples and 3 bananas
There are 2 oranges, 3 bananas and 4 apples

We can see the outcome of the format1.exe program.


The next example will format numeric data.
using System;
public class Format2
{
static void Main()
{
Console.WriteLine("{0} {1, 12}",
"Decimal", "Hexadecimal");
Console.WriteLine("{0:D}
502, 546);
Console.WriteLine("{0:D}
345, 765);
Console.WriteLine("{0:D}
320, 654);
Console.WriteLine("{0:D}
120, 834);
Console.WriteLine("{0:D}
620, 454);

{1,8:X}",
{1,8:X}",
{1,8:X}",
{1,8:X}",
{1,8:X}",

}
}

We print numbers in a decimal and hexadecimal format. We also align the numbers
using the length component.
Console.WriteLine("{0:D}
502, 546);

{1,8:X}",

The {0:D} format item specifies, the first item from the list of supplied objects will be
taken and formatted in the decimal format. The {1,8:X} format item takes the second
item. Formats it in the hexadecimal format (:X). And the string length will be 8
characters (,8). Because the number has only three characters, it is right aligned and
padded with empty strings.
$ ./format2.exe
Decimal

Hexadecimal

502

222

345

2FD

320

28E

120

342

620

1C6

Running the example we get this outcome.


The last two examples will format numeric and date data.
using System;
public class Format3
{
static void Main()
{
Console.WriteLine(string.Format("Number: {0:N}", 126));
Console.WriteLine(string.Format("Scientific: {0:E}", 126));
Console.WriteLine(string.Format("Currency: {0:C}", 126));
Console.WriteLine(string.Format("Percent: {0:P}", 126));
Console.WriteLine(string.Format("Hexadecimal: {0:X}", 126));
}
}

The example demonstrates the standard formatting specifiers for numbers. Number 126
is printed in five different formats: normal, scientific, currency, percent and
hexadecimal.
$ ./format3.exe
Number: 126.00
Scientific: 1.260000E+002
Currency: $126.00
Percent: 12,600.00 %
Hexadecimal: 7E

This is the output of the format3.exe program.


Finally, we will format date and time data.
using System;
public class Format4
{
static void Main()
{
DateTime today = DateTime.Now;
Console.WriteLine(string.Format("Short date: {0:d}", today));

Console.WriteLine(string.Format("Long date: {0:D}", today));


Console.WriteLine(string.Format("Short time: {0:t}", today));
Console.WriteLine(string.Format("Long time: {0:T}", today));
Console.WriteLine(string.Format("Month: {0:M}", today));
Console.WriteLine(string.Format("Year: {0:Y}", today));
}
}

The preceding example demonstrates the standard formatting specifiers for dates.
$ ./format4.exe
Short date: 4/11/2011
Long date: Monday, April 11, 2011
Short time: 11:14 AM
Long time: 11:14:54 AM
Month: April 11
Year: April, 2011

This is the output of the example.


This part of the C# tutorial covered strings.
C#
class FormatString
{
static void Main()
{
// Get user input.
System.Console.WriteLine("Enter a number");
string input = System.Console.ReadLine();
// Convert the input string to an int.
int j;
System.Int32.TryParse(input, out j);
// Write a different string each iteration.
string s;
for (int i = 0; i < 10; i++)
{
// A simple format string with no alignment formatting.
s = System.String.Format("{0} times {1} = {2}", i, j, (i * j));
System.Console.WriteLine(s);
}
//Keep the console window open in debug mode.
System.Console.ReadKey();
}

Substrings
A substring is any sequence of characters that is contained in a string. Use the Substring method to create
a new string from a part of the original string. You can search for one or more occurrences of a substring
by using the IndexOf method. Use the Replace method to replace all occurrences of a specified substring
with a new string. Like the Substring method,Replace actually returns a new string and does not modify
the original string. For more information, see How to: Search Strings Using String Methods (C#
Programming Guide) and How to: Modify String Contents (C# Programming Guide).
C#
string s3 = "Visual C# Express";
System.Console.WriteLine(s3.Substring(7, 2));
// Output: "C#"
System.Console.WriteLine(s3.Replace("C#", "Basic"));
// Output: "Visual Basic Express"
// Index values are zero-based
int index = s3.IndexOf("C");
// index = 7

Accessing Individual Characters


You can use array notation with an index value to acquire read-only access to individual characters, as in
the following example:
C#
string s5 = "Printing backwards";
for (int i = 0; i < s5.Length; i++)
{
System.Console.Write(s5[s5.Length - i - 1]);
}
// Output: "sdrawkcab gnitnirP"
If the String methods do not provide the functionality that you must have to modify individual characters
in a string, you can use a StringBuilder object to modify the individual chars "in-place", and then create a
new string to store the results by using the StringBuilder methods. In the following example, assume that
you must modify the original string in a particular way and then store the results for future use:
C#
string question = "hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?";
System.Text.StringBuilder sb = new System.Text.StringBuilder(question);
for (int j = 0; j < sb.Length; j++)
{
if (System.Char.IsLower(sb[j]) == true)
sb[j] = System.Char.ToUpper(sb[j]);
else if (System.Char.IsUpper(sb[j]) == true)

sb[j] = System.Char.ToLower(sb[j]);
}
// Store the new string.
string corrected = sb.ToString();
System.Console.WriteLine(corrected);
// Output: How does Microsoft Word deal with the Caps Lock key?

Null Strings and Empty Strings

An empty string is an instance of a System.String object that contains zero characters. Empty strings are
used often in various programming scenarios to represent a blank text field. You can call methods on
empty strings because they are valid System.String objects. Empty strings are initialized as follows:
string s = String.Empty;
By contrast, a null string does not refer to an instance of a System.String object and any attempt to call a
method on a null string causes a NullReferenceException. However, you can use null strings in
concatenation and comparison operations with other strings. The following examples illustrate some
cases in which a reference to a null string does and does not cause an exception to be thrown:
C#
static void Main()
{
string str = "hello";
string nullStr = null;
string emptyStr = "";
string tempStr = str + nullStr; // tempStr = "hello"
bool b = (emptyStr == nullStr);// b = false;
string newStr = emptyStr + nullStr; // creates a new empty string
int len = nullStr.Length; // throws NullReferenceException
}

Using StringBuilder for Fast String Creation


String operations in .NET are highly optimized and in most cases do not significantly impact performance.
However, in some scenarios such as tight loops that are executing many hundreds or thousands of times,
string operations can affect performance. The StringBuilder class creates a string buffer that offers better
performance if your program performs many string manipulations. The StringBuilder string also enables
you to reassign individual characters, something the built-in string data type does not support. This code,
for example, changes the content of a string without creating a new string:
C#
System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");
sb[0] = 'C';
System.Console.WriteLine(sb.ToString());
System.Console.ReadLine();
//Outputs Cat: the ideal pet
In this example, a StringBuilder object is used to create a string from a set of numeric types:
C#

class TestStringBuilder
{
static void Main()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Create a string composed of numbers 0 - 9
for (int i = 0; i < 10; i++)
{
sb.Append(i.ToString());
}
System.Console.WriteLine(sb); // displays 0123456789
// Copy one character of the string (not possible with a System.String)
sb[0] = sb[9];
System.Console.WriteLine(sb);

// displays 9123456789

}
}

using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//by using string constructor
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//methods returning string
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}",
waiting);
Console.WriteLine("Message: {0}", chat);
Console.ReadKey() ;
}
}
}
When the above code is compiled an

Potrebbero piacerti anche