Académique Documents
Professionnel Documents
Culture Documents
(Elective III)
2008-Regulations
-------------------------------------------------------------------------------------------Question Bank
UNIT-I
1) Define a) Problem Domain b) Solution Domain
Solving a problem involves conversion of problem domain or problem space to Solution domain. The
problem domain is a sector or sectors to which the problem belongs. It is an area of interest having clearly
defined boundaries. It forms an autonomous body describing high level features.
The Solution domain is the subject matter that is of concern to the computer system and the implementor
of the system. It describes the features in a manner which can be understood by the computer.
The problem domain refers to the scope of the problem being addressed by the software system. While
solving a problem using a computer ,its solution is in the form of a program.
2) Define in brief Object Oriented Principles.
OOP is based on three key principles: encapsulation, inheritance, and polymorphism. Encapsulation binds
together code and data, inheritance is the mechanism by which one class can inherit the functionality of
another, and polymorphism lets you define one interface that describes a general set of actions. These attributes
work together in a powerful way that enables the construction of reliable, reusable, and extensible programs.
n
i
.
e
b
u
et
cs
.
w
w
w
4)
Interface
It is users view point. (What
part)
It is used to interact with the
outside world
User is permitted to access the
interfaces only
It
encapsulates the knowledge
about the object.
Implementation
It is suppliers view point.
(How part)
It describes how the delegated
responsibility is carried out.
Functions or methods are
permitted to access the data.
It provides the restriction of
access data by the user.
www.csetube.in
2
An object is an instance of a class. An object has identity,state and behavior.
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.
6) Differentiate an Object and a Class.
A class is a template for creating an object. An object is an instance of a class. An object has
memory and reference.
The class is C#'s basic unit of program functionality. However, it is more than that. It is also C#'s
foundation for object-oriented programming (OOP)
7) What is .NET Framework?
.NET represents an advanced new generation of software that will drive the Next Generation Internet.
Its purpose is to make information available any time, any place, and on any device.
Quick Definition
.NET is an initiative to integrate all Microsoft products with the Next Generation web.
.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
n
i
.
e
b
u
et
cs
.
w
w
w
www.csetube.in
3
8)
a)
b)
c)
n
i
.
e
b
u
et
cs
.
w
w
w
Overview of a C# Program
Hello, world
The canonical Hello, world program can be written in C# as follows:
using System;
class Hello
www.csetube.in
4
{
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
n
i
.
e
csc hello.cs
Which produces an executable program named hello.exe. The output of the program is: Hello, world
b
u
et
cs
.
w
'\a'
alert
'\b'
Back space
'\f'
Form feed
'\n'
New line
'\r'
Carriage return
'\t'
Horizontal tab
'\v'
Vertical tab
'\''
Single quote
'\'''
Double quote
'\\'
Back slash
'\o'
null
w
w
www.csetube.in
5
The following diagram illstrates a simple C# program and explains its components one by one. This will
introduce a range of topics, from the structure of a C# program to the method of producing program
output to the screen.
Lets start by looking at a simple C# program. The complete program source is shown as below. When
the code is compiled and executed, it displays the string Hi there! in a window on the screen.
n
i
.
e
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 wouldnt have known where to
look for class Console.
b
u
et
cs
.
w
w
w
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
www.csetube.in
6
13) What are the advantages of OOP?
Code reuse
Seamless transition from different phases of s/w development
Modularity
14)
Explain the difference between a Value type and reference type. Illustrate with some examples
Value types:
* Value types can be created at compile time.
* Stored in stack memory.
* Garbage collector can't access the stack
* value types holds the data directly
* No default values will be stored in value types
* Examples for value types: Predefined datatypes,structures,enums
Reference types:
* Reference types can be created at run time.
* Stored in heap memory
* Garbage collector can access heap
* Reference types holds the data indiredtly
* Reference types holds default value
* Examples for reference types: Classes,objects,Arrays,Indexers,Interfaces
n
i
.
e
b
u
et
cs
.
w
15) 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 :
w
w
Keywords
Identifiers
Literals
Operators
Punctuators
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 :
bool
float
namespace
static
byte
for
new
string
char
foreach
private
this
catch
finally
override
throw
www.csetube.in
7
The rules for defining identifiers are :
a) They have alphabets,digits and underscore characters.
b) They must not begin with a digit.
Literals are value constants assigned to variables (or results or expressions) in a program.
The Literal types are :
Numeric Literals
Boolean
Literals
Integer literals
Real Literals
Numbers
containing
fractional parts
Character Literals
True
false
Single
character
String
'5'
'X'
Hello
World
Eg
215.95
-0.75
A real literal can
be expressed in
exponential or
scientific
notation.
0.65e4
18E3
-1.2E-1
n
i
.
e
b
u
et
cs
.
w
w
w
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
16)
Colon :
Comma ,
Period .
Parentheses ()
Braces { }
Brackets [ ]
Semicolon ;
www.csetube.in
8
17)
String literals
n
i
.
e
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.
b
u
et
cs
.
w
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 quoteescape-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.
w
w
The example
string a = "hello, world";
// hello, world
string b = @"hello, world";
// hello, world
string c = "hello \t world";
// hello world
string d = @"hello \t world";
// hello \t world
string e = "Joe said \"Hello\" to me";
// Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = @"\\server\share\file.txt";
// \\server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
www.csetube.in
9
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
category
Operators
Primary
x.y
(T)x
n
i
.
e
b
u
et
f(x)
a[x]
.cs
x++
ww
x-new
Multiplicative
Unary
Additive
sizeof
*
+
-
Shift
+
-
&
unchecked
->
false
typeof
checked
true
<<
>>
Relational and
type testing
<
>
<=
++x
>=
--x
is
www.csetube.in
10
Equality
as
-=
==
*=
!=
/=
%=
Logical AND
&
Logical XOR
Logical OR
^=
Conditional
AND
&&
<<=
&=
|=
>>=
Conditional OR
||
Conditional
?:
Assignment
??
n
i
.
e
b
u
et
+=
Arithmetic Overflow
cs
.
w
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:
w
w
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.
19) Explain with example declaration of primitive data types in C#.
www.csetube.in
11
What is Data Type?
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.
There are two types of data type in C#
1. primitive types (or) predefined
Ex: byte, short, int, float, double, long ,char, bool, DateTime, string, object etc..
2. non-primitive types (or) User Defined
Ex: class , struct , enum , interface, delegate, array.
In C#, based on what a variable contains there is two types of built-in data type
n
i
.
e
Value types
b
u
et
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.
cs
.
w
Ex: byte, short, int, float, double, long ,char, bool, DateTime.
w
w
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.
Ex: class, interface, delegate, string, object and array
Let us learn couple of data types and its uses with example
Date and Time
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.
www.csetube.in
12
Ex:
DateTime currenttime = DateTime.Now;//displays current date time.
Output:
n
i
.
e
b
u
et
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.
cs
.
w
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.
w
w
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.
www.csetube.in
13
For more information, see Classes (C# Programming Guide), Objects (C# Programming Guide), and Structs
(C# Programming Guide).
Example
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 objects 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;
}
n
i
.
e
// Instance Constructor.
public MyCustomClass()
{
Number = 0;
}
b
u
et
cs
.
w
w
w
}
// 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();
// Set the value of a public property.
myClass.Number = 27;
// Call a public method.
int result = myClass.Multiply(4);
www.csetube.in
14
}
}
}
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.
n
i
.
e
b
u
et
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:
cs
.
w
C#
w
w
www.csetube.in
15
C#
class TestMotorcycle : Motorcycle
{
public override double GetTopSpeed()
{
return 108.4;
}
static void Main()
{
TestMotorcycle moto = new TestMotorcycle();
moto.StartEngine();
moto.AddGas(15);
moto.Drive(5, 20);
double speed = moto.GetTopSpeed();
Console.WriteLine("My top speed is {0}", speed);
n
i
.
e
}
}
b
u
et
cs
.
w
w
w
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#
public void Caller()
{
int numA = 4;
// Call with an int variable.
int productA = Square(numA);
int numB = 32;
// Call with another int variable.
int productB = Square(numB);
// Call with an integer literal.
int productC = Square(12);
www.csetube.in
16
// Call with an expression that evaulates to int.
productC = Square(productA * 3);
}
int Square(int i)
{
// Store input argument in a local variable.
int input = i;
return input * input;
}
Passing by Reference vs. Passing by Value
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 valuetype 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.
n
i
.
e
b
u
et
You create a reference type by using the class keyword, as the following example shows.
cs
.
w
C#
public class SampleRefType
{
public int value;
}
w
w
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#
public static void TestRefType()
{
SampleRefType rt = new SampleRefType();
rt.value = 44;
ModifyObject(rt);
Console.WriteLine(rt.value);
}
static void ModifyObject(SampleRefType obj)
{
www.csetube.in
17
obj.value = 33;
}
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
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 ReferenceType 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:
n
i
.
e
b
u
et
cs
.
w
C#
class SimpleMath
{
public int AddTwoNumbers(int number1, int number2)
{
return number1 + number2;
}
w
w
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#
int result = obj.AddTwoNumbers(1, 2);
www.csetube.in
18
result = obj.SquareANumber(result);
// The result is 9.
Console.WriteLine(result);
C#
result = obj.SquareANumber(obj.AddTwoNumbers(1, 2));
// The result is 9.
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.
n
i
.
e
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).
b
u
et
cs
.
w
The following example illustrates the difference between value and reference parameters.
w
w
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
}
www.csetube.in
19
static void squareVal(int valParameter)
{
valParameter *= valParameter;
}
// Passing by reference
static void squareRef(ref int refParameter)
{
refParameter *= refParameter;
}
}
n
i
.
e
b
u
et
cs
.
w
w
w
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()
{
}
public Car(string color)
{
this.color = color;
}
www.csetube.in
20
A constructor can call another constructor, which can come in handy in several situations. Here is an example:
public Car()
{
Console.WriteLine("Constructor with no parameters called!");
}
public Car(string color) : this()
{
this.color = color;
Console.WriteLine("Constructor with color parameter called!");
}
n
i
.
e
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:
b
u
et
cs
.
w
w
w
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
www.csetube.in
21
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.
25) How will you create objects of a class?
Objects (C# Programming Guide)
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 objectoriented language such as C#, a typical program consists of multiple objects interacting dynamically.
n
i
.
e
b
u
et
cs
.
w
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.
w
w
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#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Other properties, methods, events...
}
class Program
{
static void Main()
www.csetube.in
22
{
Person person1 = new Person("Leopold", 6);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
// Declare new person, assign person1 to it.
Person person2 = person1;
//Change the name of person2, and person1 also changes.
person2.Name = "Molly";
person2.Age = 16;
Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/*
Output:
person1 Name = Leopold Age = 6
person2 Name = Molly Age = 16
person1 Name = Molly Age = 16
n
i
.
e
b
u
et
*/
cs
.
w
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:
w
w
C#
www.csetube.in
23
// without using "new".
Person p2 = p1;
// Assign values to p2 members.
p2.Name = "Spencer";
p2.Age = 7;
Console.WriteLine("p2 Name = {0} Age = {1}", p2.Name, p2.Age);
// p1 values remain unchanged because p2 is copy.
Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/*
Output:
p1 Name = Alex Age = 9
p2 Name = Spencer Age = 7
p1 Name = Alex Age = 9
*/
n
i
.
e
b
u
et
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.
cs
.
w
w
w
Example
The following example shows how to initialize a new StudentName type by using object initializers.
www.csetube.in
24
C#
public class Program
{
public static void Main()
{
// Declare a StudentName by using the constructor that has two parameters.
StudentName student1 = new StudentName("Craig", "Playstead");
// Make the same declaration by using a collection initializer and sending
// arguments for the first and last names. The default constructor is
// invoked in processing this declaration, not the constructor that has
// two parameters.
StudentName student2 = new StudentName
{
FirstName = "Craig",
LastName = "Playstead",
};
// Declare a StudentName by using a collection initializer and sending
// an argument for only the ID property. No corresponding constructor is
// necessary. Only the default constructor is used to process object
// initializers.
StudentName student3 = new StudentName
{
ID = 183
};
n
i
.
e
b
u
et
cs
.
w
w
w
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
}
public class StudentName
{
// The default constructor has no parameters. The default constructor
// is invoked in the processing of object initializers.
www.csetube.in
25
// You can test this by changing the access modifier from public to
// private. The declarations in Main that use object initializers will
// fail.
public StudentName() { }
// The following constructor has parameters for two of the three
// properties.
public StudentName(string first, string last)
{
FirstName = first;
LastName = last;
}
// Properties.
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public override string ToString()
{
return FirstName + " " + ID;
}
}
n
i
.
e
b
u
et
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.
cs
.
w
C#
List<StudentName>
{
new StudentName
new StudentName
new StudentName
new StudentName
};
w
w
www.csetube.in
26
{
this.name = name;
this.alias = alias;
}
To pass an object as a parameter to other methods, for example:
CalcTax(this);
To declare indexers, for example:
public int this [int param]
{
get
{
return array[param];
}
set
{
array[param] = value;
}
}
It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.
n
i
.
e
Example
b
u
et
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;
cs
.
w
w
w
// 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
{
www.csetube.in
27
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:
Employee E1 = new Employee ("John M. Trainer", "jtrainer");
// Display results:
E1.printEmployee();
}
}
Output
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
n
i
.
e
b
u
et
cs
.
w
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
w
w
www.csetube.in
28
{
public static void Main(string[] args)
{
}
}
}
public
protected
internal
private
n
i
.
e
public
b
u
et
cs
.
w
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.
w
w
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();
www.csetube.in
29
// Direct access to public members:
mC.x = 10;
mC.y = 15;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Output
x = 10, y = 15
If you change the public access level to private or protected, you will get the error message:
'MyClass1.y' is inaccessible due to its protection level.
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.
n
i
.
e
Nested types in the same body can also access those private members.
b
u
et
It is a compile-time error to reference a private member outside the class or the struct in which it is declared.
cs
.
w
For a comparison of private with the other access modifiers, see Accessibility Levels.
Example
w
w
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();
// Accessing the public field:
string n = e.name;
www.csetube.in
30
// Accessing the private field:
double s = e.AccessSalary();
}
}
In the preceding example, if you attempt to access the private members directly by using a statement like this:
double s = e.salary;
you will get the error message:
'Employee.Salary' is inaccessible due to its protection level.
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.
n
i
.
e
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:
b
u
et
class A
{
protected int x = 123;
}
class B : A
{
void F()
{
A a =
B b =
a.x =
b.x =
}
}
cs
.
w
w
w
new A();
new B();
10;
// Error
10;
// OK
The statement a.x =10 generates an error because A is not derived from B.
Struct members cannot be protected because the struct cannot be inherited.
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.
www.csetube.in
31
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;
}
class MyDerivedC: MyClass
{
public static void Main()
{
MyDerivedC mC = new MyDerivedC();
// Direct access to protected members:
mC.x = 10;
mC.y = 15;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
n
i
.
e
}
}
b
u
et
Output
x = 10, y = 15
cs
.
w
If you change the access levels of x and y to private, the compiler will issue the error messages:
w
w
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#.
www.csetube.in
32
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();
}
}
n
i
.
e
b
u
et
cs
.
w
w
w
C# Static Method
www.csetube.in
33
This program defines both static methods and regular instance
methods and calls them both. The static methods use the static
keyword somewhere in the method declaration signature,
usually as the first keyword or the second keyword after
public.
Static methods cannot access non-static class level members
and do not have a 'this' pointer. Instance methods can access
those members, but must be called through an object
instantiation, which causes another step and level of
indirection.
Program that uses instance and static methods [C#]
using System;
n
i
.
e
b
u
et
class Program
{
cs
.
w
w
w
Console.WriteLine("Static method");
}
void MethodB()
{
Console.WriteLine("Instance method");
}
www.csetube.in
34
}
char MethodD()
{
Console.WriteLine("Instance method");
return 'D';
}
n
i
.
e
//
Program.MethodA();
b
u
et
Console.WriteLine(Program.MethodC());
cs
.
w
//
// Create a new Program instance and call the two instance methods.
//
w
w
Output
Static method
Static method
C
www.csetube.in
35
Instance method
Instance method
D
n
i
.
e
b
u
et
35) How operators are classified based on symbols and names in C#?
cs
.
w
w
w
38) What are logical operators? What are different types of logical operators?
39) Classify bitwise operators and explain.
40) Write a program to illustrate bitwise operators.
41) Explain ternary operators with a diagram and example.
42) Write a C# program to illustrate ternary operation.
43) What is type conversion? Explain with examples.
44) Explain boxing and unboxing.
45) What is associativity related to evaluation of expressions?
46) How statements are classified?
47) What are control flow statements?
www.csetube.in
36
n
i
.
e
b
u
et
cs
.
w
w
w
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.
65) Write a C# program to generate Pascal triangle :
www.csetube.in
37
1
1 1
1 2
1
1 3 3
1
1 4 6 4
1
1 5 10 10 5
1
66) Develop programs to evaluate the following series :
(a)
S = x + x2+ x3+ + xn
(b)
S = 1 + 1/x + 1/x2 + 1/x3+ + 1/xn
(c) S = 1 + x + x2/2! + x3/3!+ .+xn/n!
67) Write a C# program to evaluate function
Cos(x) = 1 x2/2! + x4/4! x6/6! + ..
68) Define an array.
69) How array is represented in C#?
n
i
.
e
b
u
et
72) Write short notes on a) creation of three dimensional arrays b)creation of jagged arrays
cs
.
w
73) Write C# programs a) to read and display the array elements b) to read an array and print its
elemts in reverse order.
w
w
www.csetube.in