Cs6001 Unit I Csharp Notes Revsd
Cs6001 Unit I Csharp Notes Revsd
A C# program is basically a collection of classes. A class is defined by a set of declaration statements and
methods containing instructions known as executable statements.
Code reuse
Seamless transition from different phases of s/w development
Modularity
.NET is a software framework that includes everything requiered for developing software for web services. It
integrates presentation technologies,component technologies,and data technologies on a single platform so as to
enable users to develop internet applications as easily as thyey do on desktop systems.
In brief .NET platform provides a new environment for creating and running robust,scalable and distributed
applications over the web.
It consists of three distinct technologies
Overview of a C# Program
Hello, world
The canonical “Hello, world” program can be written in C# as follows:
using System;
class Hello
{
static void Main()
{
Console.WriteLine(“Hello, world”);
}
}
C# is a case-sensitive language: Incorrect case prevents the code from compiling successfully.
Those experienced in programming with Java, C, or C++ will immediately see similarities. Like Java, C#
inherits its basic syntax from C and C++. Syntactic punctuation (such as semicolons and curly braces), features
(such as case sensitivity), and keywords (such as class, public, and void) are familiar to programmers
experienced in these languages. Beginners and programmers from other languages will quickly find these
constructs intuitive.
Compiling and Running the Application
The default file extension for C# programs is .cs, as in hello.cs. Such a program can be compiled with the
command line directive
csc hello.cs
Which produces an executable program named hello.exe. The output of the program is: Hello, world
Line Description
Number
Line 1 Tells the compiler that this program uses types from the System namespace.
Line 3 Declares a new namespace, called Simple.
• The new namespace starts at the open curly brace on line 4 and extends through the
matching curly brace on line 12.
• Any types declared within this section are members of the namespace.
Line 5 Declares a new class type, called Program.
• Any members declared between the matching curly braces on lines 6 and 11 are
members that make up this class.
Line 7 Declares a method called Main as a member of class Program.
•In this program, Main is the only member of the Program class.
• Main is a special function used by the compiler as the starting point of the program.
Line 9 Contains only a single, simple statement; this line constitutes the body of Main.
• Simple statements are terminated by a semicolon.
• This statement uses a class called Console, in namespace System, to print out the
message to a window on the screen.
•Without the using statement in line 1, the compiler wouldn’t have known where to
look for class Console.
To compile the program, you can use Visual Studio or the command-line compiler. To use the
command-line compiler, in its simplest form, use the following command:
csc SimpleProgram.cs
13) What are tokens? What are the tokens supported in C# Language?
The smallest, non execuatable ,textual elements in a program are refered to as tokens. The compiler recognizes
them by building up expressions and statements.
In simple sterms,a C# program is a collection of tokens. C# includes the following five types of tokens :
Keywords
Identifiers
Literals
Operators
Punctuators
6
Keywords are essential part of language definition. They implement specific features of the language. They
are reserved,and cannot be used as identifiers except when they are prefacedby the @ character.
Few C# keywords are :
Literals are value constants assigned to variables (or results or expressions) in a program.
The Literal types are :
The format is
mantissa e
exponent
Operators are symbols used in expressions to describe operations involving one or more operands.
Punctuators are symbols used in grouping and seperating code. They define the shape and function of a
program.
Some Punctuators supported in C# are
7
Parentheses () Colon :
Braces { } Comma ,
Brackets [ ] Period .
Semicolon ;
16) Explain the difference between a Value type and reference type. Illustrate with some examples
Value types:
Reference types:
Boolean Literals
Two literal values are permitted for the Boolean data type. These are false and true. No other values are
valid.
bool grassIsGreen = true;
bool cowsGoBaa = false;
String literals
C# supports two forms of string literals: regular string literals and verbatim string literals.
A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and
may include both simple escape sequences (such as \t for the tab character) and hexadecimal and
Unicode escape sequences.
A verbatim string literal consists of an @ character followed by a double-quote character, zero or more
characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string
literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-
escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape
sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.
The example
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
shows a variety of string literals. The last string literal, j, is a verbatim string literal that spans multiple
lines. The characters between the quotation marks, including white space such as new line characters,
are preserved verbatim.
18) Enumerate list of operators available in C# and classify them according to their functionality.
C# Operators
C# provides a large set of operators, which are symbols that specify which operations to perform in an
expression. Operations on integral types such as ==, !=, <, >, <=, >=, binary +, binary -, ^, &, |, ~, ++, --,
andsizeof() are generally allowed on enumerations. In addition, many operators can be overloaded by the user,
thus changing their meaning when applied to a user-defined type.
The following table lists the C# operators grouped in order of precedence. Operators within each group have
equal precedence.
Operator Operators
++x
category
--x
Primary x.y
(T)x
f(x)
true
a[x]
false
x++
&
x--
sizeof
new
typeof Multiplicative *
checked /
unchecked %
-> Additive +
Unary + -
- Shift <<
! >>
~ Relational and <
10
type testing
> +=
<= -=
>= *=
is /=
as %=
Equality == &=
!= |=
^=
Logical AND &
<<=
Logical XOR ^
>>=
Logical OR | ??
Conditional &&
AND
Conditional OR ||
Conditional ?:
Assignment =
Arithmetic Overflow
The arithmetic operators (+, -, *, /) can produce results that are outside the range of possible values for the
numeric type involved. You should refer to the section on a particular operator for details, but in general:
Integer arithmetic overflow either throws an OverflowException or discards the most significant bits of
the result. Integer division by zero always throws a DivideByZeroException.
Floating-point arithmetic overflow or division by zero never throws an exception, because floating-point
types are based on IEEE 754 and so have provisions for representing infinity and NaN (Not a Number).
Decimal arithmetic overflow always throws an OverflowException. Decimal division by zero always
throws a DivideByZeroException.
When integer overflow occurs, what happens depends on the execution context, which can be checked or
unchecked. In a checked context, an OverflowException is thrown. In an unchecked context, the most
significant bits of the result are discarded and execution continues. Thus, C# gives you the choice of handling or
ignoring overflow.
In addition to the arithmetic operators, integral-type to integral-type casts can cause overflow, for example,
casting a long to an int, and are subject to checked or unchecked execution. However, bitwise operators and
shift operators never cause overflow.
11
The type of data that a variable contains is called Data Type (type). A Data Type is a classification of things
that share similar type of qualities or characteristics or behavior.
C# is strongly typed language so every variable and object must have a type.
Ex: byte, short, int, float, double, long ,char, bool, DateTime, string, object etc..
In C#, based on what a variable contains there is two types of built-in data type
Value types
A variable holds actual values then that type of data types are value types. These value types are stored in
“stack” memory and these value types are fixed in size. If you assign a value of a variable to another
variable it will create two copies.
Ex: byte, short, int, float, double, long ,char, bool, DateTime.
Reference types
A variable holds a reference to the value, then that type of data types are reference types. These reference
types are stored in “heap” memory and these types are not fixed in size. They are maintained in system
managed heap but it also uses stack to store reference of the heap. Two primitive types (string and object)
and non-primitive data types (class, interface & delegate) are examples of reference type.
Let us learn couple of data types and its uses with example
Date time is one of the most commonly used data type in C#, here i am going to explain some of properties
about it also.
12
Ex:
Output:
Output:
Classes and structs are two of the basic constructs of the common type system in the .NET Framework.
Each is essentially a data structure that encapsulates a set of data and behaviors that belong together as a
logical unit. The data and behaviors are the members of the class or struct, and they include its methods,
properties, and events, and so on, as listed later in this topic.
A class or struct declaration is like a blueprint that is used to create instances or objects at run time. If you
define a class or struct called Person, Person is the name of the type. If you declare and initialize a
variable pof type Person, p is said to be an object or instance of Person. Multiple instances of the
same Person type can be created, and each instance can have different values in its properties and fields.
A class is a reference type. When an object of the class is created, the variable to which the object is
assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the
new variable refers to the original object. Changes made through one variable are reflected in the other
variable because they both refer to the same data.
A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the
struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the
original variable therefore contain two separate copies of the same data. Changes made to one copy do not
affect the other copy.
In general, classes are used to model more complex behavior, or data that is intended to be modified after a
class object is created. Structs are best suited for small data structures that contain primarily data that is not
intended to be modified after the struct is created.
For more information, see Classes (C# Programming Guide), Objects (C# Programming Guide), and Structs
(C# Programming Guide).
Example
13
In the following example, MyCustomClass is defined with three members at the top level of
the ProgrammingGuide namespace. An instance (object) of MyCustomClass is created in the Main method
in theProgram class, and the object’s methods and properties are accessed by using dot notation.
C#
namespace ProgrammingGuide
{
// Class definition.
public class MyCustomClass
{
// Class members:
// Property.
public int Number { get; set; }
// Method.
public int Multiply(int num)
{
return num * Number;
}
// Instance Constructor.
public MyCustomClass()
{
Number = 0;
}
}
// Another class definition. This one contains
// the Main method, the entry point for the program.
class Program
{
static void Main(string[] args)
{
// Create an object of type MyCustomClass.
MyCustomClass myClass = new MyCustomClass();
A method is a code block that contains a series of statements. A program causes the statements to be
executed by calling the method and specifying any required method arguments. In C#, every executed
instruction is performed in the context of a method. The Main method is the entry point for every C#
application and it is called by the common language runtime (CLR) when the program is started.
Method Signatures
Methods are declared in a class or struct by specifying the access level such as public or private, optional
modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters.
These parts together are the signature of the method.
Method parameters are enclosed in parentheses and are separated by commas. Empty parentheses indicate
that the method requires no parameters. This class contains three methods:
C#
Method Access
Calling a method on an object is like accessing a field. After the object name, add a period, the name of the
method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The
methods of the Motorcycle class can therefore be called as in the following example:
C#
15
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
}
}
The method definition specifies the names and types of any parameters that are required. When calling code
calls the method, it provides concrete values called arguments for each parameter. The arguments must be
compatible with the parameter type but the argument name (if any) used in the calling code does not have to
be the same as the parameter named defined in the method. For example:
C#
int Square(int i)
16
{
// Store input argument in a local variable.
int input = i;
return input * input;
}
By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore,
changes to the argument have no effect on the original copy in the calling method. You can pass a value-
type by reference by using the ref keyword. For more information, see Passing Value-Type Parameters (C#
Programming Guide). For a list of built-in value types, see Value Types Table (C# Reference).
When an object of a reference type is passed to a method, a reference to the object is passed. That is, the
method receives not the object itself but an argument that indicates the location of the object. If you change
a member of the object by using this reference, the change is reflected in the argument in the calling
method, even if you pass the object by value.
You create a reference type by using the class keyword, as the following example shows.
C#
Now, if you pass an object that is based on this type to a method, a reference to the object is passed. The
following example passes an object of type SampleRefType to method ModifyObject.
C#
The example does essentially the same thing as the previous example in that it passes an argument by value
to a method. But, because a reference type is used, the result is different. The modification that is made
17
inModifyObject to the value field of the parameter, obj, also changes the value field of the argument, rt, in
the TestRefType method. The TestRefType method displays 33 as the output.
For more information about how to pass reference types by reference and by value, see Passing Reference-
Type Parameters (C# Programming Guide) and Reference Types (C# Reference).
Return Values
Methods can return a value to the caller. If the return type, the type listed before the method name, is
not void, the method can return the value by using the return keyword. A statement with
the return keyword followed by a value that matches the return type will return that value to the method
caller. The return keyword also stops the execution of the method. If the return type is void,
a return statement without a value is still useful to stop the execution of the method. Without
the return keyword, the method will stop executing when it reaches the end of the code block. Methods
with a non-void return type are required to use thereturn keyword to return a value. For example, these two
methods use the return keyword to return integers:
C#
class SimpleMath
{
public int AddTwoNumbers(int number1, int number2)
{
return number1 + number2;
}
To use a value returned from a method, the calling method can use the method call itself anywhere a value
of the same type would be sufficient. You can also assign the return value to a variable. For example, the
following two code examples accomplish the same goal:
C#
C#
Console.WriteLine(result);
Using an local variable, in this case, result, to store a value is optional. It may help the readability of the
code, or it may be necessary if you need to store the original value of the argument for the entire scope of
the method.
In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function
members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that
change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword. For simplicity,
only the ref keyword is used in the examples in this topic. For more information about the difference between ref and out,
see ref (C# Reference), out (C# Reference), and Passing Arrays Using ref and out (C# Programming Guide).
The following example illustrates the difference between value and reference parameters.
C#
class Program
{
static void Main(string[] args)
{
int arg;
// Passing by value.
// The value of arg in Main is not changed.
arg = 4;
squareVal(arg);
Console.WriteLine(arg);
// Output: 4
// Passing by reference.
// The value of arg in Main is changed.
arg = 4;
squareRef(ref arg);
Console.WriteLine(arg);
// Output: 16
}
// Passing by reference
static void squareRef(ref int refParameter)
{
refParameter *= refParameter;
}
}
19
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such
as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are
the signature of the method.
public Car()
In our example for this chapter, we have a Car class, with a constructor which takes a string as argument. Of
course, a constructor can be overloaded as well, meaning we can have several constructors, with the same name,
but different parameters. Here is an example:
public Car()
this.color = color;
A constructor can call another constructor, which can come in handy in several situations. Here is an example:
public Car()
}
20
this.color = color;
If you run this code, you will see that the constructor with no parameters is called first. This can be used for
instantiating various objects for the class in the default constructor, which can be called from other constructors
from the class. If the constructor you wish to call takes parameters, you can do that as well. Here is a simple
example:
this.color = color;
If you call the constructor which takes 2 parameters, the first parameter will be used to invoke the
constructor that takes 1 parameter.
Destructors
Since C# is garbage collected, meaing that the framework will free the objects that you no longer use,
there may be times where you need to do some manual cleanup. A destructor, a method called once an
object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very
much like other methods in C#. Here is an example of a destructor for our Car class:
~Car()
Console.WriteLine("Out..");
Once the object is collected by the garbage collector, this method is called.
21
A class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory
that has been allocated and configured according to the blueprint. A program may create many objects of the same class.
Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code
is the code that uses these variables to call the methods and access the public properties of the object. In an object-
oriented language such as C#, a typical program consists of multiple objects interacting dynamically.
Because classes are reference types, a variable of a class object holds a reference to the address of the object on the
managed heap. If a second object of the same type is assigned to the first object, then both variables refer to the object at
that address. This point is discussed in more detail later in this topic.
Instances of classes are created by using the new operator. In the following example, Person is the type
and person1 and person 2 are instances, or objects, of that type.
C#
class Program
{
static void Main()
{
Person person1 = new Person("Leopold", 6);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
}
}
/*
Output:
person1 Name = Leopold Age = 6
person2 Name = Molly Age = 16
person1 Name = Molly Age = 16
*/
Because structs are value types, a variable of a struct object holds a copy of the entire object. Instances of structs can also
be created by using the new operator, but this is not required, as shown in the following example:
C#
The memory for both p1 and p2 is allocated on the thread stack. That memory is reclaimed along with the type or
method in which it is declared. This is one reason why structs are copied on assignment. By contrast, the memory that is
allocated for a class instance is automatically reclaimed (garbage collected) by the common language runtime when all
references to the object have gone out of scope. It is not possible to deterministically destroy a class object like you can in
C++. For more information about garbage collection in the .NET Framework, see Garbage Collection.
You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for
the type.
The following examples show how to use object initializers with named objects. The compiler processes object initializers
by first accessing the default instance constructor, and then by processing the member initializations. Therefore, if the
default constructor is declared as private in the class, object initializers that require public access will fail.
Anonymous types must be declared with an object initializer. For more information, see How to: Return Subsets of
Element Properties in a Query (C# Programming Guide).
Example
The following example shows how to initialize a new StudentName type by using object initializers.
C#
System.Console.WriteLine(student1.ToString());
System.Console.WriteLine(student2.ToString());
System.Console.WriteLine(student3.ToString());
System.Console.WriteLine(student4.ToString());
}
// Output:
// Craig 0
// Craig 0
// 183
// Craig 116
}
// Properties.
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
The following example shows how to initialize a collection of StudentName types by using a collection initializer. Note
that a collection initializer is a series of comma-separated object initializers.
C#
this
Visual Studio .NET 2003
The this keyword refers to the current instance of the class. Static member functions do not have a this pointer.
The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.
26
Example
In this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar
names. It is also used to pass an object to the method CalcTax, which belongs to another class.
// keywords_this.cs
// this example
using System;
public class Employee
{
public string name;
public string alias;
public decimal salary = 3000.00m;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
}
public class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
// Display results:
E1.printEmployee();
}
}
Output
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
27
C# programs can consist of one or more files. Each file can contain one or more namespaces. A namespace can contain
types such as classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces. The following is
the skeleton of a C# program that contains all of these elements.
// A skeleton of a C# program
using System;
namespace MyNamespace1
{
class MyClass1
{
}
struct MyStruct
{
}
interface IMyInterface
{
}
delegate int MyDelegate();
enum MyEnum
{
}
namespace MyNamespace2
{
}
class MyClass2
{
public static void Main(string[] args)
{
}
}
}
Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the
four access modifiers:
public
protected
internal
private
public
Visual Studio .NET 2003
28
The public keyword is an access modifier for types and type members. Public access is the most permissive access level.
There are no restrictions on accessing public members.
For a comparison of public with the other access modifiers, see Accessibility Levels.
Example
In the following example, two classes are declared, MyClass1 and MyClass2. The public members x and y of
the MyClass1 are accessed directly from MyClass2.
// protected_public.cs
// Public access
using System;
class MyClass1
{
public int x;
public int y;
}
class MyClass2
{
public static void Main()
{
MyClass1 mC = new MyClass1();
Output
x = 10, y = 15
If you change the public access level to private or protected, you will get the error message:
private
Visual Studio .NET 2003
The private keyword is a member access modifier. Private access is the least permissive access level. Private members are
accessible only within the body of the class or the struct in which they are declared.
Nested types in the same body can also access those private members.
It is a compile-time error to reference a private member outside the class or the struct in which it is declared.
For a comparison of private with the other access modifiers, see Accessibility Levels.
29
Example
In this example, the Employee class contains a public member, Name, and a private member, Salary. The public member
can be accessed directly, while the private member must be accessed through the public methodAccessSalary().
// private_keyword.cs
using System;
class Employee
{
public string name = "xx";
double salary = 100.00; // private access by default
public double AccessSalary() {
return salary;
}
}
class MainClass
{
public static void Main()
{
Employee e = new Employee();
In the preceding example, if you attempt to access the private members directly by using a statement like this:
double s = e.salary;
protected
Visual Studio .NET 2003
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is
declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class
type. For example, consider the following code segment:
class A
{
protected int x = 123;
}
class B : A
{
30
void F()
{
A a = new A();
B b = new B();
a.x = 10; // Error
b.x = 10; // OK
}
}
The statement a.x =10 generates an error because A is not derived from B.
It is an error to reference a protected member from a class, which is not derived from the protected member's class.
For more information on protected members, see 3.5.3 Protected access for instance members.
For a comparison of protected with the other access modifiers, see Accessibility Levels.
Example
In this example, the class MyDerivedC is derived from MyClass; therefore, you can access the protected members of the
base class directly from the derived class.
// protected_keyword.cs
using System;
class MyClass
{
protected int x;
protected int y;
}
Output
x = 10, y = 15
If you change the access levels of x and y to private, the compiler will issue the error messages:
internal
Visual Studio .NET 2003
The internal keyword is an access modifier for types and type members. Internal members are accessible only within files
in the same assembly. For more information on assemblies, see Components and Assemblies.
A common use of internal access is in component-based development because it enables a group of components to
cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for
building graphical user interfaces could provide Control and Form classes that cooperate using members with internal
access. Since these members are internal, they are not exposed to code that is using the framework.
It is an error to reference a member with internal access outside the assembly within which it was defined.
Caution An internal virtual method can be overridden in some languages, such as textual Microsoft intermediate
language (MSIL) using Ilasm.exe, even though it cannot be overridden using C#.
For a comparison of internal with the other access modifiers, see Accessibility Levels.
Example
This example contains two files, Assembly1.cs and Assembly2.cs. The first file contains an internal base
class, BaseClass. In the second file, an attempt to access the member of the base class will produce an error.
File Assembly1.cs:
// Assembly1.cs
// compile with: /target:library
internal class BaseClass
{
public static int IntM = 0;
}
File Assembly2.cs
// Assembly2.cs
// compile with: /reference:Assembly1.dll
// CS0122 expected
class TestAccess
{
public static void Main()
{
BaseClass myBase = new BaseClass(); // error, BaseClass not visible outside assembly
}
}
C# Static Method
32
using System;
class Program
{
static void MethodA()
{
Console.WriteLine("Static method");
}
void MethodB()
33
{
Console.WriteLine("Instance method");
}
char MethodD()
{
Console.WriteLine("Instance method");
return 'D';
}
Output
Static method
Static method
C
Instance method
Instance method
D
35) How operators are classified based on symbols and names in C#?
38) What are logical operators? What are different types of logical operators?
51) Explain with syntax and flowchart a) While loop construct b) Do while loop construct c)for loop
construct
52) Write a C# program to check whether the given year is Leap Year or not.
59) Write a program to find the factorial of a non-negative integer using recursion.
60) How exceptions are handled in C# programs?
62) Explain the syntax of a) the throw statement b) the try statement c) user defined exceptions
36
63) Write C# program to illustrate exception handling a) for stack over flow b) divide by zero
exception
64) What are checked and unchecked statements? Write a C# program to illustrate this.
72) Write short notes on a) creation of three dimensional arrays b)creation of jagged arrays
73) Write C# programs a) to read and display the array elements b) to read an array and print its
elemts in reverse order.
81) Write a C# program to find the area under the curve 1/1+x2 using Trapezoidal rule.