Unit1 Part2
Unit1 Part2
Unit1 Part2
• This means that all types, whether they represent business objects or are
primitive types such as numbers, share the same basic set of functionality.
CONT…
• For example, any type can be converted to a string by calling its ToString
method.
Classes and interfaces:
• In a traditional object-oriented paradigm, the only kind of type is a class.
• In C#, there are several other kinds of types, one of which is an interface.
• An interface is like a class except it is only a definition for a type, not an
implementation.
CONT…
• Identifiers are names that programmers use for their classes, methods,
variables, arrays and so on.
• An identifier must be a whole word, essentially made up of Unicode
characters starting with a letter or underscore and subsequent characters
may be letter, underscore or number.
• C# identifiers are case-sensitive.
• By convention, parameters, local variables, and private fields should be in
camel case (e.g., firstName), and all other identifiers should be in Pascal
case (e.g., GetFullName).
KEYWORDS
• Keywords are names reserved by the compiler that developers can’t use as
identifiers.
• These are special to the compiler.
• These are the keywords in our example program: using, class, static, void, int,
string and so on.
• But we can use an identifier that clashes with a reserved keyword,
• we can do so by qualifying it with the @ prefix.
For instance:
class class {...} // Illegal
class @class {...} // Legal
ACCESS MODIFIERS
• All types and type members have an accessibility level, which controls whether they can
be used from other code in assembly or other assemblies.
public:
The type or member can be accessed by any other code in the same assembly or
another assembly that references it.
private:
The type or member can be accessed only by code in the same class or struct.
protected:
The type or member can be accessed only by code in the same class, or in a class that
is derived from that class.
VARIABLE
• A variable represents a storage location that has a modifiable value.
• To use variables, programmers have to declare them.
• This means that programmers have to assign them a name and a type.
• Once you have declared variables you can use them as storage units for the type
of data that you declared them to hold.
Variable declaration:
<access_modifiers> <type> <variable_name>;
Example: int a=2; string myString;
STRING TYPE C#’S
• string type (aliasing the System.String type) represents an immutable
(unchangeable) sequence of Unicode characters.
• string is a reference type, rather than a value type.
• A string literal is specified inside double quotes:
string a = "Heat";
• To avoid this problem. A verbatim string literal is prefixed with @ and does not
support escape sequences.
string a1 = "\\\\server\\fileshare\\helloworld.cs";
OR string a2 = @"\\server\fileshare\helloworld.cs";
String Concatenation
• The + operator concatenates two strings:
string s = "a" + "b"; Or s += “c”;
String Interpolation
• A string preceded with the $ character is called an interpolated string.
int x = 4;
Console.Write ($"A square has {x} sides"); // A square has 4 sides
• C# will convert the expression to a string by calling its ToString method or equivalent
Null and empty strings
• We can create empty string using the static string.Empty field or empty literal.
Exampe: string str=string.Empty; OR string str=“”;
• The static string.IsNullOrEmpty method is a useful shortcut for testing whether a given
string is either null or empty.
Manipulating Strings
• IndexOf is more powerful to search string. IndexOfAny is similar.
• It returns the first position of a given character or substring (or -1 if the substring isn’t
found):
Console.WriteLine ("abcde".IndexOf ("cd")); // 2
• LastIndexOf is like IndexOf, but works backward through the string. LastIndexOfAny
is similar.
Contd…
• String is immutable, all the methods that “manipulate” a string return a new one, leaving
the original untouched (same for when reassign a string variable).
• Substring extracts a portion of a string:
string left3 = "12345".Substring (0, 3); // left3 = "123";
string end3 = "12345".Substring (2); // end3 = "345";
• Trim function remove whitespace characters (including spaces, tabs, new lines, and
Unicode variations of these) from the beginning or end of a string;
• Replace replaces all (nonoverlapping) occurrences of a particular character or substring:
• ToUpper and ToLower return upper and lowercase versions of the input string.
• Split divides a string up into pieces: string[] words = "The quick brown fox".Split();
String.Format
• The static Format method provides a convenient way to build strings that embed
variables.
• Format simply calls ToString on them.
• When calling String.Format, you provide a composite format string followed by each of
the embedded variables.
Eg. string composite = “Your username:{0} and password:{1} ";
string s = string.Format (composite, “user123”, “pass123");
Arrays
• An array represents a fixed number of variables (called elements) of a particular
type.
• The elements in an array are always stored in a contiguous block of memory,
providing highly efficient access.
• An array is denoted with square brackets after the element type.
type[ ] arrayName;
For example:
char[] vowels = new char[5]; // Declare an array of 5 characters
• The Length property of an array returns the number of elements in the array.
CONTD…
• An array initialization expression to declare and populate an array in a single step:
char[] vowels = new char[] {'a','e','i','o','u'};
OR char[] vowels = {'a','e','i','o','u'};
• All arrays inherit from the System.Array class, providing common services for all arrays.
• These members include methods to get and set elements regardless of the array type.
Multidimensional Arrays
• Multidimensional arrays come in two varieties: rectangular and jagged.
• Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are
arrays of arrays.
Rectangular arrays:
• Rectangular arrays are declared using commas to separate each dimension.
• The following declares a rectangular two-dimensional array, where the dimensions are
• 3 by 3:
int[,] matrix = new int[3,3];
Jagged Arrays
• Jagged arrays are declared using successive square brackets to represent each dimension.
• Example of declaring a jagged two-dimensional array, where the outermost dimension is
3:
int[][] matrix = new int[3][];
Fields:
• A field is a variable that is a member of a class and can hold data of the class. For
example:
class Student
{
string name;
int age = 10;
}
CONTD..
Properties:
• Provide access to a class attribute (a field). Useful for exposing fields in components. A
property is declared like a field, but with a get/set block added.
public class Student
{
string firstName;
public string FirstName
{
get{ return firstName; }
set{ firstName=value; }
}
}
Methods(Functions)
• Methods implement some actions/operations that can be performed by an
object on the data.
• It can receive input data from the caller by specifying parameters and
output data back to the caller by specifying a return type.
• It can specify a void return type, indicating that it doesn’t return any value
to its caller.
• A method’s signature must be unique within the type.
• A method’s signature comprises its name and parameter types (but not the
parameter names, nor the return type).
CONTD..
Function declaration:
<accessibilityLevel><returnType><functionName>(paramType paramName);
Implementation:
<accessibilityLevel><returnType><functionName>(paramType paramName, . . . . . . )
{ Code }
public class Calculator
{
public int Sum(int a, int b)
{
return a+b;
}
}
Constructor
• Special function its name same with the class name then it is called constructor. But it has
no return type.
• It can initialize data member of new object. Constructor may be with parameter or
without parameter. In C#, default constructor is automatically created.
public class Student
{
stringfirstName;
public Student(string fName)
{
firstName=fName;
}
}
Object
• It is instance of class which hold values of object.
• The new operator is used to create an object or instantiate an object.
• The "new" operator can invoke the constructor.
• Any object of the reference type is assigned a null value unless it is declared using the
new operator.
• The new operator assigns space in the memory to the object only during run time
Student objStudent = new Student();
objStudent is an object of Student class.
Inheritance
• A class can inherit from another class to extend or customize the original class.
• Inheriting from a class lets you reuse the functionality in that class instead of building it from
scratch.
• A class can inherit from only a single class, but can itself be inherited by many classes, thus
forming a class hierarchy.
In this example,
public class Asset
{
public string Name;
}
• Next, we define classes called Stock and House, which will inherit from Asset.
• Stock and House get everything an Asset has, plus any additional members that they define:
CONTD…
public class Stock : Asset // inherits from Asset
{
public long SharesOwned;
}
public class House : Asset // inherits from Asset
{
public decimal Mortgage;
}
Here’s how we can use these classes:
Stock stock = new Stock { Name="MSFT", SharesOwned=1000 };
Console.WriteLine (stock.Name); // MSFT
Console.WriteLine (stock.SharesOwned); // 1000
Polymorphism
• Generally, polymorphism is a combination of two words, poly, and another one is
morphs.
• Here poly means “multiple” and morphs means “forms” so polymorphism means many
forms.
• Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
• When a message can be processed in different ways is called polymorphism.
Polymorphism Provides Following Features:
• It allows us to invoke methods of derived class through base class reference during
runtime.
• It has the ability for classes to provide different implementations of methods that are
called through the same name.
• Polymorphism is of two types:
• Compile time polymorphism/Overloading
• Runtime polymorphism/Overriding
Compile Time Polymorphism
• Compile time polymorphism is method and operators overloading.
• It is also called early binding.
• In overloading method performs the different task at the different input parameters.
Runtime Time Polymorphism
• Runtime time polymorphism is done using inheritance and virtual functions.
• Method overriding is called runtime polymorphism.
• It is also called late binding.
• When overriding a method, you change the behavior of the method for the derived class.
• Overloading a method simply involves having another method with the same prototype.
Abstract Classes
• A class is declared as abstract using the abstract keyword.
• We can't create an instance of an abstract class. Instead, only its concrete sub classes can
be instantiated.
• The purpose of an abstract class is to provide a blueprint for derived classes.
• An abstract class can implement code with non-Abstract methods.
Abstract Members
• Abstract classes are able to define abstract members.
• Abstract members are like virtual members, except they don’t provide a default
implementation.
• Abstract members must be overridden in any non-abstract derived class.
• An abstract method is implicitly a virtual method.
CONTD…
public abstract class Animal
{
public abstract string Eat(); //abstract method with no implementation
}
Nested Types
A nested type is declared within the scope of another type.
public class TopLevel
{
public class Nested { } // Nested class
public enum Color { Red, Blue, Tan } // Nested enum
}