Advance C# FeaturesAdvance C# Features
Access ModifiersAccess Modifiers
• public– Access is not restricted.
• protectedAccess is limited to the containing class or types derived– Access is limited to the containing class or types derived from the containing class.
• internall d h bl– Access is limited to the current assembly.
• protected internal– Access is limited to the current assembly or types derived y ypfrom the containing class.
• private– Access is limited to the containing type– Access is limited to the containing type.
Default Accessibility LevelsDefault Accessibility Levels
• enum– only public
• class– private by default– can be any of the five modifiers.
• interface• interface– only public
• struct– private by default– can be public, internal or private
BoxingBoxing
Transformation of a value type to a reference type.Transformation of a value type to a reference type.
UnboxingUnboxing
Transformation of a reference type to a value type.Transformation of a reference type to a value type.
Classes & StructuresClasses & Structures
• Essentially templates from which we canEssentially templates from which we can create objects.
• Each object has some data and methods to• Each object has some data and methods to manipulate and access that data.
K d i d i i l• Keyword new is used to instantiate class or structure.e.g. <class/structure name> objectName=new <class/structure name>(parameters if any);
StructuresStructures
• Special kind of class that is a value type.• Ease of creation and also permits for making a copy with just a use
of an equals sign.• Data members in a structure are private by default as compared to
C++C++• Instances of a structure take up extra stack space.• Syntax
t t < t t >struct <structure name>{
(constructors, constants, fields, methods, properties, indexers operators events and nested types)indexers, operators, events, and nested types)
}You can not initialize the fields of structure without constructor
Class MembersClass Members
• Data & Functions within a class are called asData & Functions within a class are called as Class Members.
• Data Members :Which contain data for classData Members : Which contain data for class such as fields, events and constants.
• Function Members :Which provide someFunction Members : Which provide some functionality to manipulate some data in the class. Include methods, property, constructors, finalizers, operators, and indexers.
MethodsMethods
• Special purpose function to perform someSpecial purpose function to perform some task.
• Can be instance methods or static methods.Can be instance methods or static methods.• Declaration similar to C/C++ or Java.• Can be one of four types• Can be one of four types.
– Don’t take parameter and Don’t return value.– Take parameter but Don’t return value– Take parameter but Don t return value.– Don’t take parameter but return value.– Take parameter and return valueTake parameter and return value.
MethodsMethods
• Declaration Syntaxec a at o Sy ta[access modifier] [return type] <function name> (parameters if any)
{}e ge.g.public int Add(int number1,int number2){{return (number1+number2);
}
MethodsMethods
• Calling Syntax (Same as C/C++ or Java)public int Add(int number1,int number2){
return (number1+number2);}...Add(5,10); //Works correctlyAdd 5,10 //Compilation ErrorAdd 5,10 //Compilation Error...
Parameter PassingParameter Passing
• Pass by value (Default)Pass by value (Default)
• Pass by reference
Pass by referencePass by reference
• ref keyword is used in function declaration as well as function invocation.
static void SomeFunction(int[] ints, ref int i){{
ints[0] = 100;i = 100; // the change to i will persist after //
SomeFunction() exitsSomeFunction() exits}...SomeFunction(ints, ref i);
Pass by referencePass by reference
• ref keyword is used in function declaration as well as function invocation.
static void SomeFunction(int[] ints, ref int i){
ref keyword used to declare method taking parameter as
reference.{ints[0] = 100;i = 100; // the change to i will persist after //
SomeFunction() exitsSomeFunction() exits}...SomeFunction(ints, ref i); ref keyword used to pass variable as
referencereference.
out Keywordout Keyword
• New in C#.• Provides support to return more than one value from a function.static void SomeFunction(out int i){
i = 100;}public static int Main(){
int i; // note how i is declared but not initializedSomeFunction(out i);( );Console.WriteLine(i);return 0;
}}
Method OverloadingMethod Overloading
• Declaring methods with same name but different signatures.
class ResultDisplayer{
void DisplayResult(string result){
// implementation}void DisplayResult(int result){{
// implementation}
}}
Method OverloadingMethod Overloading• C# does not support default variable declaration. Use method
overloading for same purposesoverloading for same purposes.
class MyClass{{
int DoSomething(int x) // want 2nd parameter with default value 10{
DoSomething(x, 10);g( , );}int DoSomething(int x, int y){
// implementation}
}
Operator OverloadingOperator Overloading
• Something similar to C++ developers.• Allows the use of operators with class objects instead of
just using methods or properties.e.g. To multiply two matrices we can have a code like thise.g. To multiply two matrices we can have a code like thisMatrix A,B,C;//assume A,B,C have been initialized
Without Operator OverloadingC=A.Add(B);( )
With Operator OverloadingC=A+B;C=A+B;
Operator OverloadingOperator Overloading
• SyntaxSyntaxpublic static <return type> operator <operator symbol> (parameters)
{
//Operation
}
e.g. public static Vector +(Vector lhs, Vector rhs)g p ( , )
{
Vector result=new Vector(lhs.x+rhs.x, lhs.y+rhs.y, lhs.z+rhs.z);
return result;return result;
}
Operator Overloading RulesOperator Overloading Rules
• Must be declared staticMust be declared static.
• Must be public in nature.
C i b l d d i• Comparison operators must be overloaded in pairs and their return type must be bool.
== and !=,< and > , >= and <
• If you overload == and != operators, Equals() and GetHashCode() methods must also be overridden.
Operators which can be overloadedOperators which can be overloadedCategory Operators Restrictions
Arithmetic binary + ,‐ ,* ,/, % None
Arithmetic Unary + ,‐ , ++ ,‐‐ None
Bitwise binary &, |, ^, <<, >> None.
Bitwise unary !,~ true AND false
The true and false operators must be overloaded as a pair.
Comparison ==,!= AND <,> AND <=,>= Must be overload as a pair.
Assignment +=, ‐=, *=, /=, >>=, & |
You cannot explicitly l d h<<=, %=, &=, |=, ^= overload these operators;
they are overridden implicitly when you override the individual operators such as +, ‐, %, and so on.
Operators which can be overloadedOperators which can be overloadedCategory Operators Restrictions
Index [] You cannot overload the index operator directly. Theindexer member type allows you to support the index operator on yourindex operator on your classes and structs.
Cast () You cannot overload the cast operator directly. User p ydefined casts allow you to define custom cast behavior.
Strings and Regular ExpressionsStrings and Regular Expressions
• What is a string?What is a string?
• Difference between string and StringBuilder
i f d?• How strings are formatted?
• What is a regular expression?
• Writing a regular expression.
What is a string?What is a string?
• A sequence of charactersA sequence of characters.
• Everything written in double quotes.
Ch b d i h lik• Characters can be accessed with an array like syntax.
‐e.g. string str=“Hello”;
str[0] returns ‘H’[ ]
• Strings are immutable.
What is a StringBuilder?What is a StringBuilder?
• Similar to stringsSimilar to strings
• Mutable that is can be changed.
• Found in System Text namespace• Found in System.Text namespace.
• More efficient that string class but less powerful.
• Usage– StringBuilder bd=new StringBuilder(“Hello”);
bd.Append(“,World”);
• Two main properties Capacity and Length
Formatting of stringsFormatting of strings
• string myName=“World”;Console.WriteLine(“Hello {0}”,myName);
prints“Hello World”
because the string myName is written at 0th index in WriteLinemethod
• Syntax for formatting an item{index[,alignment][:formatString]}The matching braces ("{" and "}") are required.
• Use string.Format(…) method to format the item. Similar to Console.WriteLine() except that it returns a value.
Formatting of stringsFormatting of strings
e.g. int myInt=100;Console.WriteLine(“Value is {0:C}”,myInt);Console.WriteLine(“Value is {0:D}”,myInt);Console.WriteLine(“Value is {0,10:D}”,myInt);Console.WriteLine(“Value is {0,‐10:D}”,myInt);
The output is (Culture is US English)$100.00100
100100
Common FormattersCommon FormattersC‐CurrencyD‐DecimalN‐NumberX‐HexadecimalG General(Default)G‐General(Default)P‐PercentE‐Scientific
d‐Short DateD‐Long Datet‐ Short timeT‐ Long timeM‐MonthY‐Year
Regular ExpressionsRegular Expressions
• A language designed specifically for languageA language designed specifically for language processing.e.g.e.g. ‐ dir *.txt when used from dos prompt lists all the files with extension “.txt”the files with extension .txt‐ dir re* lists all directories or files starting with “re”.with re .
• Regular expressions use many of such characters to actually filter the data.characters to actually filter the data.
With regular expressions we canWith regular expressions we can
• Identify repeated words in a string e.g. “The y p g gcomputer books books” to “The computer books”
• Convert all words to title case e.g. “This is to test” to “This Is To Test”to “This Is To Test”.
• Convert all words greater than 3 characters long to title case e.g. “this is to test” to “This is toto title case e.g. this is to test to This is to Test”.
• Ensure that sentences are properly capitalized.• Separate various element names of a URI e.g. given http://www.google.com, extract the protocol computer name file name and so onprotocol, computer name, file name, and so on
Writing Regular ExpressionsWriting Regular ExpressionsSymbol Meaning Example Matches^ Beginning of input text ^B B but only if first character in text^ Beginning of input text ^B B, but only if first character in text$ End of input text X$ X, but only if last character in text. Any single character except
the newline character (\n) i.ation isation, ization* Preceding character may be g y
repeated 0 or more times ra*t rt, rat, raat, raaat, and so on+ Preceding character may be
repeated 1 or more times ra+t rat, raat, raaat and so on, (but not \trt)? Preceding character may be
repeated 0 or 1 times ra?t rt and rat only\s Any whitespace character \sa [space]a, \ta, \na (\t and \n have
the same meanings as in C#)\S Any character that isn’t a
whitespace \SF aF rF cF but not \tfwhitespace \SF aF, rF, cF, but not \tf
\b Word boundary ion\b Any word ending in ion\B Any position that isn’t a
word boundary \BX\B Any X in the middle of a wordy \ \ y
Writing Regular ExpressionsWriting Regular Expressions
e.g. \bion matches transition, ionization …e.g. \bion matches transition, ionization …[a‐z]* matches any lowercase string
including null stringincluding null string [a‐z]+ matches any lowercase string that is
not nullnot null[a‐z]? matches any lowercase string that is
either null or 1 character long.either null or 1 character long.[a‐zA‐Z]{1} matches any string of length 1
containing only alphabetcontaining only alphabet
PropertiesProperties• Just like methods dressed to look like Fields to client code.
H i ht i t f i d f• e.g. Height is a property for a windows form.
Mainform.Height=30;
• Syntax• Syntax[access modifier] [Data Type] <Property Name>{
get{
return [Data Type Object];}setset{
//Set the property}
}}
PropertiesProperties
• e.g.public string SomeProperty{
get{
return “This is the property value”;}}set{
// do whatever needs to be done to set the //property
}}
PropertiesProperties• e.g.
bli t i S P tpublic string SomeProperty{
get{
Must have same data type{
return “This is the property value”;}setset{
// do whatever needs to be done to set the //propertyvalue keyword is used to get the passed value.
}}
Read Only PropertiesRead Only Properties
• Read Only Properties are declared by omitting ead O y ope t es a e dec a ed by o tt gthe set accessor.
public string SomeProperty{
tget{
return “This is the property value”;return This is the property value ;}
}
ConstructorsConstructors• Same name as class name• No return type• Can be overloaded each with different signature.• Automatically supplied if no constructor is defined in the class.• C# support creation of static constructors• C# support creation of static constructors
public class MyNumber{{
private int number;public MyNumber(int number){{
this.number = number;}
}}
Static ConstructorsStatic Constructors
• A no parameter constructoro pa a ete co st ucto• Declared with static keyword• No access modifiers are definedNo access modifiers are defined• Can be executed any time decided by CLR• Executed when the class is loadedExecuted when the class is loaded• Executed only once not every time an instance is created
• Guaranteed to be invoked before first call to any member of class
Static ConstructorsStatic Constructors
• SyntaxSy taclass MyClass{{static MyClass(){
// initialization code}// rest of class definition
}
Static ConstructorsStatic Constructors
• SyntaxSy taclass MyClass{{static MyClass(){
No access modifier specified for static constructor
// initialization code}// rest of class definition
}
Constructors for StructuresConstructors for Structures
• Same as class constructors but can’t defineSame as class constructors but can t define constructors with no parameter
• Zero parameter constructor is always created• Zero parameter constructor is always created implicitly
U d i i i li h fi ld f h if• Used to initialize the fields of the structure if they are needed to be
Classes Vs StructuresClasses Vs Structures
Structure Class• Value Types• Stored on stack
• Reference Types
• Stored on heap• Keyword struct• Does not support i h it
Stored on heap
• Keyword class
• Supportsinheritance• Used for smaller data type for
• Supports inheritance
U d i ldata type for performance reasons.
• Used in general
InheritanceInheritance
• A way to extend the functionality of existingA way to extend the functionality of existing classes
• Derived class contains all the functionalities of• Derived class contains all the functionalities of the base class plus can have its own functionalitiesfunctionalities
• C# does not support Multiple Inheritance
• Can be Implementation inheritance or Interface inheritance
Implementation InheritanceImplementation Inheritance
• Derived class takes all members fields andDerived class takes all members fields and functions from base class
• Derived class uses base class’s implementation• Derived class uses base class s implementation of each function unless overridden by derived classclass
• Most useful to add new functionality to i i lexisting classes
Interface InheritanceInterface Inheritance
• Derived class inherits only signatures ofDerived class inherits only signatures of existing functions not their implementations
• Acts like a contract to follow by the derived• Acts like a contract to follow by the derived classes
M f l h if• Most useful to when we want to specify a type that makes certain features available
What is Assembly?What is Assembly?
• A logical unit that contains the compiled codeA logical unit that contains the compiled code targeted at .NET Framework.
• Self describing because contains metadata• Self describing because contains metadata.
• Can be stored in more than one file with any fil h i ione file having an entry point.
• Some can be stored in memory not in files at all. Referred to as dynamic assembly.
Types of assembliesTypes of assemblies
• Shared AssembliesShared Assemblies
• Private Assemblies
Private AssembliesPrivate Assemblies
• Simplest type of assembliesSimplest type of assemblies.
• Specific to the software.
• Used only by the software for which it is written• Used only by the software for which it is written.
• Must be in the same folder as application t bl it bf ldexecutable or its subfolder.
• Simple installation (Zero Compact or XCopyI t ll ti )Installation).
• No registry entries at all.
Shared AssembliesShared Assemblies
• Common libraries.Co o b a es.• Any application can use.• Can not be installed just by copyingCan not be installed just by copying• Risks involved
– Name collisionsa e co s o s– Version overwriting
• Solution– Global Assembly Cache (GAC)
• Need a strong name
Global Assembly Cache (GAC)Global Assembly Cache (GAC)
• Contains all the shared assemblies installed inContains all the shared assemblies installed in the system.
• Stored at• Stored at
<windows drive letter>:\Windows\assembly
• All assemblies have unique strong names.
Strong NameStrong Name
• Unique name for an assemblyUnique name for an assembly.
• Strong name consists ofName of assembly– Name of assembly
– Version of assembly
– Public key generated by strong cryptographic methods– Public key generated by strong cryptographic methods
– Culture
• To create strong name for an assembly at visual• To create strong name for an assembly at visual studio command prompt>sn –k mykey snk>sn k mykey.snk
Associate assembly with Strong NameAssociate assembly with Strong Name
• Set the AssemblyKeyFile attributeSet the AssemblyKeyFile attribute
• Above the class declaration type
[ bl bl il (“ / / k k”)][assembly:AssemblyKeyFile(“../../mykey.snk”)]
Shared assembly installationShared assembly installation
• use Gacutil utility provided with Visual Studiouse Gacutil utility provided with Visual Studio
• In visual studio command prompttil /i bl fil dll>gacutil /i <assemblyfile.dll>
• The assembly is installed to GAC.
Viewing AssembliesViewing Assemblies
• Open Visual Studio command promptOpen Visual Studio command prompt
• Typeild>ildasm
• Choose the assembly file either .dll or .exe
• That’s done.
Features of assembliesFeatures of assemblies
• Self describingSelf describing
• Version dependencies
Sid b id l di• Side by side loading
• Application isolation is ensured in application domains.