Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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
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
Note
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.
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.
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.
//
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 function
String Functions
Definitions
Clone()
CompareTo()
Contains()
EndsWith()
Equals()
GetHashCode()
GetType()
GetTypeCode()
IndexOf()
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()
IsNormalized()
LastIndexOf()
Length
Remove()
This method deletes all the characters from beginning to specified index
position.
Replace()
Split()
StartsWith()
Substring()
ToCharArray()
Trim()
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
whether
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
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 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);
We create an empty StringBuilder object. We append three strings into the object.
$ ./initialization.exe
C#
NetBeans
MySql
C#
Fields of glory
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";
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;
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
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 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.
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;
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");
}
}
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);
}
}
}
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
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);
'T');
'h');
'e');
' ');
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);
}
}
}
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);
}
The Contains() method returns True if the string contains a specific character.
Console.WriteLine(str.IndexOf("e"));
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
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
}
}
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
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
{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
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
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
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
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?
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
}
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