You are on page 1of 29

1

CS1010 ‐ C# and .NET Framework


Two Marks
UNIT I
What is Application Framework?
A set of classes and-or libraries used to implement the standard structure of an application for a
specific operating system is called as application framework. They provide structure and services for
application development. Application frameworks are extensible, modular, and reusable.

What is boxing?
Converting a value type to a reference type object is called boxing. A value type is stored on stack
memory and requires conversion—boxing—to an object on the heap memory before it can be treated as
an object. The members of the new object can be invoked on the value, e.g., converting a double to a
string. Boxing may be performed implicitly at runtime by the CLR.
Ex:
int m = 10;
object om = m;
m = 20;
Console.WirteLine (m); // m = 20
Console.WriteLine (om); //om = 10

What is Unboxing?
Conversion of a reference typed object to the associated value type instance. Usually, unboxing is
performed explicitly by a cast operation.
Ex:
int m = 10;
object om = m;
int n = (int) om;

What are advantage of foreach statement over the for statement?


The advantage of foreach over the for statement is that it automatically detects the boundaries of
the collection being iterated over. Further, the syntax includes a built - in iterator for accessing the
current element in the collection.

What are difference between Structures and Classes

Category Classes Structs


Data Type Reference type and therefore stored on Value type and therefore stored on
the heap the stack.
Inheritance Support Inheritance Do not support inheritance
Default Default value of a class type is null Default value is the value produced by
Values ‘zeroing out’ the fields of the struct.
Field Permit initialization of instance fields Do not permit initialization of
initialization instance fields.
Constructors Permit declaration of paramerterless Do not permit declaration of
constructors parameterless constructor
Destructor Supported Not Supported
Assignment Assignment copies the reference Assignment copies the values.
Einstein College

Define Common Language Runtime (CLR)


CLR is the .NET runtime environment responsible for program execution management and for
providing container services—debugging, exception management, memory management, profiling, and
security. The CLR is a major subsystem in the .NET Framework which implements the Common Type
System. Also this is called as Virtual Execution System (VES).

What are the services provided by the CLR?


• Loading and execution of programs.
• Memory isolation for applications.
• Verification of type safety
• Compilation of IL into native executable code
• Providing metadata
• Memory Management (automatic garbage collection)
• Enforcement of Security
• Interoperability with other systems.
• Managing exceptions and errors
• Support for tasks such as debugging and profiling.

What are the benefits of CLR?


• Interoperability with other languages
• Enhanced security
• Versioning support
• Debugging support
• Automatic garbage collection
• XML support for web-based applications

List out the components of CLR


a) Common Type System
b) Intermediate Language (IL)
c) Execution Support Functions
d) Security
e) Garbage Collection
f) Class Loader
g) Memory Layout

Define Common Language Specification (CLS)


CLS is a subset of the Common Type System and a set of conventions for promoting
interoperability between programming languages and the .NET Framework. CLS details conventions that
must be followed by class library authors and by programming language designers.

Define Common Type System (CTS)


CTS is the .NET Framework specification for defining, declaring, and managing types in .NET
languages for the Common Language Runtime (CLR). All .NET components must comply with the CTS
specification.

What is Framework Class Library (FCL)?


FCL comprises the thousands of classes constituting the foundation of the .NET Framework. FCL
services include core functionality—collections, file and network I/O, system service access, value types,
etc.—, database interaction, desktop-based application support—Windows Forms—, Web-based
application support—Web Forms—, Web services support, and XML support.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 3 Dept. of CSE

What is Just‐In‐Time (JIT)?


JIT is the process of compiling MSIL code units just when needed at runtime. The JIT compiler in
the Common Language Runtime (CLR) compiles MSIL instructions to native machine code as a .NET
application is being executed. Compilation occurs when a method is called and is not compiled more than
once during program execution; because, JIT-compiled code is cached in memory.

What is Managed code?


Code that is executed by the Common Language Runtime (CLR) is called managed code. Managed
code provides metadata to enable the CLR to handle exceptions, locate methods encoded in assembly
modules, and manage security information. Managed code can access both managed data and
unmanaged data.

What is unmanaged code?


It is, also called unsafe code, code that executes outside of the control of the Common Language
Runtime (CLR). Unmanaged code may perform unsafe operations such as pointer arithmetic. Unmanaged
code is used for accessing unmanaged memory, calling Windows APIs, interfacing to COM components,
and coding performance-critical methods which avoid the overhead of the CLR.

What is Managed data?


Data in memory allocated and deallocated by the Common Language Runtime (CLR). Managed
data can be accessed only by managed code.

What is unmanaged data?


Data allocated outside of the control of the Common Language Runtime (CLR). Unmanaged data
is accessible by both managed and unmanaged code.

What is Microsoft Intermediate Language (MSIL)?


.NET language compilers—e.g., C# and VB.NET— compile source code into MSIL—a machine-
independent, intemediate language. MSIL is subsequently compiled by the Just-In-Time (JIT) compiler into
machine language just prior to execution. The Native Image Generator Tool can also be used to convert
MSIL into machine language.

What is .NET?
The .NET Framework comprises:
• Common Language Runtime (CLR);
• .NET Framework Class Library;
• .NET languages including C#;
• Visual Studio.NET IDE.
.NET supports multiple languages making it suitable for cross-platform applications. All .NET
languages must comply with the Common Language Specification (CLS)—an agreement encompassing the
specifications for .NET languages. Microsoft offers four .NET languages—Visual Basic .NET, Visual C#,
Visual C++ with managed extensions, and Jscript.
The CLR comprises an execution engine, a garbage collector, a just-in-time (JIT) compiler, a security
system, and the .NET Framework fundamentals.

What is NET Framework?


Microsoft programming infrastructure for creating, deploying, and executing applications and
services that use .NET technologies. .NET Framework comprises three major components - Common
Language Runtime (CLR), Framework Base Classes and ASP.NET

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 4 Dept. of CSE

What are the benefits of .NET approach?


Some of the major benefits are:
• Simple and faster systems development
• Rich object model
• Enhanced built-in functionality
• Many different ways to communicate with the outside world
• Integration of different languages into one platform
• Easy deployment and execution
• Wide range of scalability
• Interoperability with existing applications
• Simple and easy-to-build sophisticated development tools
• Fewer bugs
• Potentially better performance.

Write a short on Framework Base Classes.


.NET supplies a library of base classes that can be used to implement applications quickly. These can be
used by simply instantiating them and invoking their methods or by inheriting them through derived
classes, thus extending their functionality. Much of the functionality resides in the namespace called
System. The System namespace contains classes for many different tasks including:
• Input/Output Operations
• String handling
• Managing arrays, lists, maps, etc
• Accessing files and file systems.
• Accessing the registry
• Security
• Windowing
• Windows messages
• Database Management
• Evaluation of mathematical functions
• Drawing
• Managing errors and exceptions
• Connecting to Internet
• And many more

What are the tools provided by .NET framework for managing user and application interfaces?
• Windows forms
• Web forms
• Console Applications
• Web services

What are .NET languages?


Native Languages
a) C# (created specially for .NET framework)
b) C++ (Managed code)
c) Visual Basic
d) Jscript
Third-Party Languages
a) COBOL
b) Eiffel
c) Perl
d) Python
e) Small Talk

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 5 Dept. of CSE

f) Mercury
g) Scheme

What is Abstract IL?


ILX is a toolkit for accessing the contents of .NET Common IL binaries. Features include
transforming binaries into structured abstract syntax trees to be manipulated.

What is Regular expression?


A regular expression—also called regex, regexes, regexp, regexps, and regexen—is a string that
describes a set of strings to be found or altered according to certain syntax rules. The regular expression
pattern matching process is supported by programming languages, text editors, and utilities. A regular
expression may include alphanumeric characters, metacharacters, and operators. Most .NET languages—
including Visual C#—support regular expressions.

Define Virtual Execution System (VES)?


VES is the environment for executing managed code. VES defines a virtual machine. Thus, VES
supports execution of the Common Intermediate Language instruction set. Also, VES provides support for
built-in data types, a set of control flow constructs, and a model for exception handling.

What are the major highlights of C#?


• It simplifies and modernizes C++
• It is the only component-oriented language available today.
• It is the only language designed for the .NET Framework
• It combines the best features of many commonly used languages: the productivity of visual basic,
the power of C++ and the elegance of Java
• It is intrinsically object-oriented and web-enabled.
• It has a lean and consistent syntax.

List out some problems of C and C++


• They have long cycle-time.
• They are not truly object-oriented.
• They are not suitable for working with new web technologies.
• The have poor type-safety.
• They are prone to costly programming errors.
• They do not support versioning.
• They are prone to memory leakages.
• They are weak in consistency

What is the limitation of Visual Basic?


Since Visual Basic is not truly an object-oriented programming language, it becomes increasingly difficult
to use when systems become large.

What are the limitations of using Java language?


• Java has not retained some powerful C++ features such as operator overloading.
• It also lacks inter-operability with code developed in other languages.

What are important features of C#, which are adopted from other languages?
C# borrows Java’s features such as grouping of classes, interfaces and implementation together in one file
so that programmers can edit the code more easily. C# also handles objects using references, the same
way as Java.
C# borrows VB’s approach to form design, namely, dragging controls from a tool box, dropping them onto
forms, and writing event handlers for them.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 6 Dept. of CSE

WHAT IS C#?
C# (pronounced as 'c’ sharp') is a new computer-programming language developed by Microsoft
Corporation, USA.
C# is a fully object-oriented language like Java and is the first Component-oriented language. It
has been designed to support the key features of .NET Framework, the new development
platform of Microsoft for building component-based software solutions.
It is a simple, efficient, productive and type-safe language derived from the popular C and C++
languages. Although it belongs to the family of C / C++, it is a purely objected-oriented, modem
language suitable for developing Web based applications.

What is Characteristic of C#?


1. Simple
2. Consistent
3. Modern
4. Object - Oriented
5. Type - Safe
6. Versionable
7. Compatible
8. Interoperable
9. Flexible

What are the APPLICATIONS OF C#?


. Console applications
. Windows applications
. Developing Windows controls
. Developing ASP.NET projects
. Creating Web controls
. Providing Web services
. Developing .NET component library

List out the features of C++, which are dropped in C#?


The following features of C++ are missing in C#:
1. Macros
2. Multiple Inheritance
3. Templates
4. Pointers
5. Global Variables
6. typedef statement
7. Default arguments
8. Constant member functions or parameters
9. Forward declaration of classes.

What are the enhancements done to C++ in C# environment?


C# modernizes C++ by adding the following new features:
1. Automatic Garbage Collection
2. Versioning support
3. Strict type-safety.
4. Properties to access data members
5. Delegates and events
6. Boxing and unboxing
7. Web Services.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 7 Dept. of CSE

What are the components included in the .NET platform?


a) .NET infrastructure and tools
b) .NET user experience
c) .NET building block
d) .NET device software

Write a short note on OLE technology.


OLE (Object Linking and Embedding) technology was developed by Microsoft in the early 1990s to enable
easy interprocess communications. OLE provided support to achieve the following:
To embed documents from one application into another application.
To enable one application to manipulate objects located in another application.
Ex: interoperability between MS-Excel and MS-Word

What is component based approach? What are the benefits of COM?


In the component-based approach, a program is broken into a number of independent components
where each one offers a particular service. Each component can be developed and tested independently
and then integrated into the main system.
COM Technology offers a number of benefits to developers and users. It
reduces the overall complexity of software
enables distributed development across multiple organizations or departments and
enhances software maintainability.

List out the two types C# programs?


C# can be used to develop two categories of programs, they are,
a) Executable application programs (.exe)
b) Component Libraries (.dll)

What is Command Line Argument?


There may be occasions when we may like our program to behave in a particular way depending
on it input provided at the time of execution. This is achieved in C# by using what are known as
command line arguments. Command line arguments are parameters supplied to the Main method at the
time of invoking it for execution.

What is comment? List out its types?


The statements which are not included for compilation by the compiler are called as comments. They are
used to enhance readability and understanding of code. C# permits two types of comments, namely:
Single Line Comments
Begins with a double backslash (//) symbol. Ex: //Main method begins
Multi Line Comments
This starts with /* characters and terminates with */.
Ex: /* Program - Testing Delegates
Date - 09.10.08
Developer - Kumaran */

Can Main() method return a value? If so how?


Main() can also return a value if it is declared as int type instead of void. When the return type is int, a
return statement is included at the end of the method.
The value returned by the Main() method is serves as program’s termination status code. The purpose of
this code is to allow communication of success of failure to the execution environment.
Ex:
using System;
class TestMain
{

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 8 Dept. of CSE

public static void Main()


{
bool flag = 0;
if (flag)
{
Console.WriteLine(“TRUE”);
return 0;
}
else
{
Console.WriteLine(“FALSE”);
return 1;
}
}
}

How will you alias a namespace class?


The general form to alias a namespace class is,
using alias-name = class-name;
Ex:
using Test = System.Console; //Test is alias for System.Console
class TestAlias
{
public static void Main()
{
Test.WriteLine(“Hello!”);
}
}

Can we use multiple Main() in a program? If so how?


C# includes a feature that enables us to define more than one class with the Main method. Since Main is
the entry point for program execution as well as there should be only one entry point during execution.
This problem is resolved by specifying which Main() is to be used for compilation. For compilation,
csc filename.cs /main:classname
Now, even though there is more than one Main() only one Main() method is considered for the
compilation.

State the C# Program Structure.


C# program contains following sections in it:
a) Documentation Section
b) Using Directive Section
c) Interfaces Section
d) Classes Section
e) Main Method Section

C# is a freeform language. Comment


C# is a freeform language. So it does not care where on the line the code is begins.
Ex:
System.Console.WriteLine(“Hello ECE”);
Can be written as
System.Console.WriteLine
(“Hello ECE”);
Can be written as

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 9 Dept. of CSE

System.Console.WriteLine
(
“Hello ECE”
)
;

What are the types of tokens available in C#?


C# has five types of tokens. They are,
a) Keywords
b) Identifiers
c) Literals
d) Operators
e) Punctuators

What are keywords?


Keywords are an essential part of a language definition. They implement specific features of the language.
They are reserved, and cannot be used as identifiers except when they are prefaced by the @ character.
There are 79 keywords in C#. Ex: public, private, if, while etc..

What are identifiers?


Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, labels,
namespaces, interfaces, etc. C# identifiers enforce the following rules:
They can have alphabets, digits and underscore characters.
They must not begin with a digit
Upper case and lower case letters are distinct
Keywords in stand-alone mode cannot be used as identifiers
C# permits the use of keywords as identifiers when they are prefixed with a ‘@’ character.

What are the lexical elements of C#?


1. Comments
2. white spaces
3. tokens
4. preprocessing directives

What is line terminator in C#?


A new line character is known as line terminator in C#. The following characters are treated as line
terminators:
• The carriage return character (U+000D)
• The line feed character (U+000A)
• The carriage return character followed by a line feed character.
• The line separator character (U+2028)
• The paragraph separator character (U+2029)

What are punctuators?


Punctuators are symbols used for grouping and separating code. They define the shape and function of a
program. Punctuators or Separators in C# include:
a) Parentheses ()
b) Braces { }
c) Brackets []
d) Semicolon ;
e) Colon :
f) Comma ,
g) Period .

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 10 Dept. of CSE

What is stack memory and heap memory?


Stack - Represents a portion of memory that can be used by the program at runtime. This memory is not
subject to garbage collection. The lifetime of the variables stored in stack is limited to the lifetime of the
block in which it is defined. Method states are allocated on stack. Thus, local variables, arguments of
methods, and local object references are allocated on stack memory.
Heap - This is the region of memory used for dynamic storage. It is reserved for a program to use for the
temporary storage of data structures whose existence or size cannot be determined until the program is
running. It is subjected to garbage collection. The problem of memory leak is avoided in this type of
memory allocation.

What is value type?


It includes simple data types such as enum, struct, char, bool, int, float, etc.
Value type variable directly contain data since memory is allocated on stack.
Operation on one variable does not affect the other value type variable.
It provides efficient access and faster execution by stack allocation.

What is reference type?


It includes class types, interface types, delegate types and array types.
Reference variable stores references to objects whereas the data of objects are stored in
locations represented by references.
Reference variable points to an object allocated on heap.
Reference variable can have null value.
One or more reference variables can be assigned with the same reference of an object. Hence,
operation on one reference variable may affect the object referenced by the other reference
variable.

What are statements?


Statements in C# are like sentences in natural languages. A statement is an executable combination of
tokens ending with a semicolon. C# implements several types of statements. They include:
Empty Statements
Labeled statements
Declaration statements
Expression statements
Selection statements
Interaction statements
Jump statements
The try statements
The checked statements
The unchecked statements
The lock statements
The using statements

What are escape sequences?


C# supports special backslash character constants that are used in output methods. These character
combinations are called as escape sequences. Some escape sequences are:
\n new line
\t horizontal tab
\f form feed
\r carriage return
\b backspace

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 11 Dept. of CSE

What is NaN?
Floating-point data types support a special value known as Not‐a‐Number (NaN). NaN is used to
represent the result of operations such as dividing zero by zero, where an actual number is number is not
produced. Most operations that have NaN as an operand will produce NaN as a result.

List out reference data types?


The reference types can also be divided into two groups:
User-defined (or complex) types
Predefined (or simple) types
User-defined reference types refer to those which are defined by the user using predefined type. They
include,
Classes
Interfaces
Delegates
Arrays
Predefined reference types include two data types:
Object type
String type

Which types of variables are initialized with default value?


The following categories of variables are automatically initialized to their default values.
Static variables
Instance variables
Array elements

What is the default value for built‐in data types?


All integer type 0
char type ‘\x000’
float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference types null

How constants are created in C#?


The constants can be created by using any one of the method:
using const keyword
Ex: const int ROW = 10;
const float PI = 3.14;
using #define statement (symbolic constants)
Ex: #define ROW 10
#define PI 3.14

What are the advantages of using constants?


Constants make programs easier to read and understand
Easy to modify the program.
They minimize accidental errors, like attempting to assign values to some variables which are
expected to be constants.

Classify the C# operators.


C# operators can be classified into a number of related categories as below:
a) Arithmetic operators

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 12 Dept. of CSE

b) Relational operators
c) Logical operators
d) Assignment operators
e) Increment and decrement operators
f) Conditional operators
g) Bitwise operators
h) Special operators

What are special operators available in C#?


C# supports the following special operators:
is (relational operator)
as (relational operator)
typeof (type operator)
sizeof (size operator)
new (object operator)
.(dot) (member-access operator)
checked (overflow checking)
unchecked (prevention of overflow checking)

What is the advantage of using foreach loop?


The advantage of foreach over for statement is that it automatically detects the boundaries of the
collection being iterated over. Further, the syntax includes a built-in iterator for accessing the current
element in the collection.

What is method modifier? List out all method modifiers available in C#?
The modifiers decide the nature of accessibility and the mode of application of the method.
Modifier Description
new The method hides an inherited method with the same signature.
public The method can be accessed from anywhere, including outside the class
protected The method can be accessed from within the class to which it belongs, or a type
derived from that class.
internal The method can be accessed from within the same program.
private The method can only be accessed from inside the class to which it belongs.
static The method does not operate on a specific instance of the class.
virtual The method can be overridden by a derived class.
abstract A virtual method which defines the signature of the method, but doesn’t provide an
implementation.
override The method overrides an inherited virtual or abstract method.
sealed The method overrides an inherited virtual method, but cannot be overridden by any
classes which inherit from this class. Must be used in conjunction with override. extern
The method is implemented externally, in a different language.

What are types of parameters available?


C# employs four kinds of parameters:
Value parameters - used to pass the parameters by value
Reference parameters - used to pass the parameters by reference
Output parameters - used to pass the results back from a method
Parameter arrays (using param) - used to pass a variable number of parameters

Write a short note on pass by value.


By default, method parameters are passed by value. When a method is invoked, the values of actual
parameters are assigned to the corresponding formal parameters. The value of the actual parameter that
is passed by value to a method is not changed by any changes made to the corresponding formal

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 13 Dept. of CSE

parameter within in the body of the method.


Ex:
using System;
class PassByValue
{
static int increment(int val)
{
return ++val;
}
public static void Main()
{
int a = 10;
Console.WriteLine(“Value of a - before calling increment is “ + a);
Console.WriteLine(“Value returned by increment is “ + increment(a);
Console.WriteLine(‘Value of a - after calling increment is {0}”, a);
}
}
Output:
Value of a - before calling increment is 10
Value returned by increment is 11
Value of a - after calling increment is 10

Write a short note on pass by reference.


Unlike a value parameter, a reference parameter does not create a new storage location. Instead, it
represents the same storage location as the actual parameter used in the method invocation. Remember,
when a formal parameter is declared as ref, the corresponding argument in the method invocation must
also be declared as ref.
Ex:
using System;
class PassByRef
{
static void increment(ref int val)
{
++val;
}
public static void Main()
{
int a = 10;
Console.WriteLine(“Value of a - before calling increment is “ + a);
increment( ref a);
Console.WriteLine(‘Value of a - after calling increment is {0}”, a);
}
}
Output:
Value of a - before calling increment is 10
Value of a - after calling increment is 11

Write a short note on output parameters.


Output parameters are used to pass results back to the calling method. This is achieved by declaring the
parameters with an out keyword. Similar to reference parameter, an output parameter does not create a
new storage location. Instead, it becomes an alias to the parameter in the calling method. When a formal
parameter is declared as out, the corresponding actual parameter in the calling method must also be
declared as out.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 14 Dept. of CSE

Ex:
using System;
class Output
{
static void addition (int a , int b, out int result)
{
result = a + b;
}
public static void Main()
{
int x = 5, y = 8, sum;
addition(x, y, out sum);
Console.WriteLine(“The sum of {0} and {1} is {2}”, x, y, sum);
}
}

Write a short note on parameter arrays (OR) params keyword (OR) variable argument list
In C#, the methods can be defined to handle variable number of arguments using what are known as
parameter arrays. Parameter arrays are declared using the keyword params. This can be combined with
the formal parameter list and in such cases, it must be the last parameter.
It is permitted to use parameter arrays along with the value parameters, but it is not allowed to combine
the params modifier with the ref and out modifiers.
Ex:
using System;
class ParamsTest
{
static int sum(params int[] val)
{
int tot=0;
foreach (int i in val)
tot = tot + i;
return tot;
}
public static void Main()
{
Console.WriteLine(“The sum of 40,50,60 is {0}”, sum(40,50,60));
Console.WriteLine(“The sum of 2,3,12,15,17 is {0}”, sum(2,3,12,15,17));
Console.WriteLine(“The sum of 12 is {0}”, sum(12));
}
}
Output:
The sum of 40,50,60 is 150
The sum of 2,3,12,15,17 is 49
The sum of 12 is 12

How the compiler selects a method for compilation?


The method selection involves following steps:
1. The compiler tries to find an exact match in which the types of actual parameters are the
same and uses that method.
2. If the exact match is not found, then the compiler tries to use the implicit conversions to the
actual arguments and then uses the method whose match is unique. If the conversion
creates multiple matches, then the compiler will generate an error message.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 15 Dept. of CSE

Can a method return more than one value in C#? Justify your answer.
Any method can return only one value if the return type is other than void. But in C#, it is possible to
return more than one value from the program using out parameter. For example,
using System;
class ReturnTest
{
static int test(int a, out int b)
{
b = a + a;
return ++a;
}
public static void Main()
{
int x = 10, y;
Console.WriteLine(“The value of x is {0}”, test(x,out y));
Console.WriteLine(“The value of y is {0}”, y);
}
}
Output:
The value of x is 11
The value of y is 20

What are the advantages of using structures?


They are created much more quickly than heap-allocated types.
They are instantly and automatically deallocated once they go out of scope.
It is easy to copy value type variables on the stack.

Differentiate Regular and Jagged Arrays


Regular Arrays Jagged Arrays
It is an array of elements of non-array type. It is array of elements of array type.
Multidimensional array subscripts are separated Each array subscript is enclosed within separate
by commas within an open and its closing square square brackets.
brackets.
Shapes are regular Shapes are not regular.
The elements are stored in the subsequent All the elements may not be stored in
locations subsequent locations. The elements of each
array type will be stored in a linear order.
Its declaration contains only one pair of square Its declaration contains two or more pairs of
brackets. square brackets.

Comparison of Virtual and non‐virtual method


Virtual Method Non‐Virtual Method
Implementation of a virtual method can be The implementation of a non-virtual method is
changed by a derived class. fixed.
The override method is required in the derived No need for the override method.
class to change the implementation
The keyword static, abstract or override can not Non-virtual method may include the keyword
be used along with the keyword virtual in a static, abstract or override.
virtual method.
The runt-time type of object determines the Compile-time type of object determines the
method to be invoked. method to be invoked.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 16 Dept. of CSE

Difference between using new and override modifier


Effects of using new modifier Effects of using override modifier
Inclusion of the new modifier is to indicate that Inclusion of override modifier is to change the
the base member is intentionally hidden by the implementation of a method in the derived class
derived member. If new is not included, the that has same signature in its base class.
compiler issues warning. This warning is
suppressed by adding new modifier.
It is not possible to have both new and override The override modifier cannot be included with
modifiers in the same declaration. new, static, or virtual.
Both virtual and non-virtual methods may use Only virtual method in the base class can be
new modifier in a derived class to hide its base overridden in the derived class. Hence, the
methods. virtual method in a base class has a
corresponding override method with the same
signature. Non-virtual methods cannot be
overridden by using override modifier.
If a new modifier is included in a method Only by including override modifier in a method
declaration that doesn’t have the same signature it is possible to override another method. In all
in its base class, a warning is issued by the other cases, the method with the same signature
compiler. This warning is suppressed by in the derived class simply hides the inherited
removing the new modifier. method.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 17 Dept. of CSE

UNIT II
What is a class?
A class is essentially a description of how to construct an object that contains fields and methods. It
provides a sort of template for an object and behaves like a basic data type such as int. Classes provide a
convenient approach for packing together a group of logically related data items and functions that work
on them.

Differentiate Class and Structure


Structure Class
A structure is a value type A class is a reference type
Only constructor with parameters is allowed Constructor with parameter or without
parameter is allowed.
Destructor is not allowed. Destructor is allowed.
A structure is inherited from object. No further Inheritance is fully supported.
inheritance is supported.
Fields are of primitive data type. Any data type is allowed as fields.
A structure variable is passed by value and not as A class variable is passed as reference and not as
reference even if it is created using new value.
operator.

What are the three pillars of OOP?


All object-oriented languages employ three core principles, namely,
encapsulation
inheritance
polymorphism
These are often referred to as three ‘pillars’ of OOP.

Write a note on encapsulation?


Encapsulation provides the ability to hide the internal details of an object from its users. The outside user
may not be able to change the state of an object directly. However, the state of an object may be altered
indirectly using what are known accessor and mutator methods. The concept of encapsulation is also
known as data hiding or information hiding.

What is inheritance?
Inheritance is the concept used to build new classes using the existing class definitions. Through
inheritance a class can be modified easily. The original class is known as base or parent class and the
modified one is known as derived class or subclass or child class.
The concept of inheritance facilitates the reusuability of existing code and thus improves the integrity of
programs and productivity of programmers.

What is polymorphism?
Polymorphism is the ability to take more than one form. The behavior of the method depends upon the
types of data used in the operation. This is extensively used while implementing inheritance.

What are instance variables? Why they are called so?


Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables
are called instance variables because they are created whenever an object of the class is instantiated.
These are also known as member variables.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 18 Dept. of CSE

What is the Characteristic of Inheritance?


1. A derived class extends its direct base class. It can add new members to those it inherits.
However, it cannot change or remove the definition on an inherited member.
2. Constructor and destructors are not inherited. All other members, regardless of their
declared accessibility in base class, are inherited.
3. All instance of a class contains a copy of all instance fields declared in the class and its base
classes.
4. A derived class can hide an inherited member.
5. A derived class can override an inherited member.

Advantages of Inheritance
1. Reuse the existing code and extend the functionality.
2. Add new members to the derived class to specialize the class.
3. replace the implementation of existing methods by overriding a method that already exists in the
base class. use of virtual and override methods help to exhibit polymorphic behavior.
4. Organize software components into categories and subcategories resulting in classification of
software. Classification is the most widely accepted use of inheritance although other
mechanisms may also be used for classification.

List out the member access modifiers in C#


private - Member is accessible only within the class containing the member.
public - Member is accessible from anywhere outside the class as well. It is also accessible in
derived classes.
protected - Member is visible only to its own class and its derived class.
internal - Member is available within the assembly or component that is being created but not to
the clients of the component.
protected internal - Available in the containing program or assembly and in the derived classes.

What is the use of static?


The members that are declared static are called static members. Since these members are associated with
the class itself rather than with individual objects, the static variables and static methods are often
referred to as class variables and class methods in order to distinguish them from their counterparts,
instance variables and instance methods. The static variables and methods are called using class names
rather than object name.

What are the restrictions for using static methods?


Static methods have several restrictions. They are,
They can only call other static methods.
They can only access static data.
They cannot refer to this or base in any way.

What are features of static members?


A static member is a part of a class and not part of an object of that class. It performs a common
task for all objects of a class.
There is exactly one copy of a static member, no matter how many objects are created.
A static member is accessed using the notation ClassName.StaticMemberName.
The method body of a static method of a class cannot reference a non-static variable of that
class. It can access only the static fields and static methods of that class.
A static member can be accessed in the static method body directly in the same manner as an
instance member in an instance method.
A non-static variable can be passed as a parameter to a static method. Thus, it is possible to use
the value of an instance variable in a static method by passing it as a parameter to it. Also, by

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 19 Dept. of CSE

passing an explicit object reference as a parameter to the static method, non-static members
may be accessed in it.
A static constructor is used to initialize static variables. It is invoked only once, no matter how
many objects were created.

What is a constructor?
A constructor is a special method declared in a class to initialize the fields at the time of the creation of an
instance (object) of a class. it is a special method because the name of the method is same as the class.

What are the features of a constructor?


The name of the constructor is the same as the class.
A constructor does not return any value and hence does not have a return type.
The formal parameters define the signature of the constructor.
A constructor initializer cannot access the object being created.
A constructor is called when an object is created.

What is default constructor?


A public parameterless constructor is called default constructor. And it is implicitly declared for any class.
Even though there is no constructor in the class this default constructor will be invoked and initializes the
member with default value of that type.
Simply, the process called instantiation is done through calling the constructor only.

What is the use of static constructors?


A static constructor is called before any object of the class is created. This is useful to do any
housekeeping work that needs to be done once. It is usually used to assign initial values to static data
members. The restrictions while using static constructors are:
It cannot have any parameters
It cannot have any access modifier
A class can have only one static constructor

What are the features of a static constructor?


Static constructors are automatically invoked. They cannot be explicitly invoked.
The static constructor for a class is first executed before
a. Its object is created
b. Any static member of the class is referenced.
A static constructor never execute more than once.
Access modifier is not allowed.

What is the use of private constructors?


C# does not have global variables or constants. All declarations must be contained in a class. But using
static members this can be achieved some what. Such classes are never required to instantiate objects
because; object is not needed to access the static members of a class. Creating objects for such classes
may be prevented by using private constructor to the class.

What is copy constructor?


A copy constructor creates an object by copying variables from another object. But there is no copy
constructor provided in C#. It should be defined by the programmer.
Ex: public Point(Point pt)
{ x = pt.x;
y = pt.y;
}
The copy constructor is invoked when instantiating the object of type Point. For example,
Point p2 = new Point(p1);

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 20 Dept. of CSE

What is destructor?
A destructor is opposite to a constructor. It is a method called when an object is no more required. The
name of the destructor is the same as the class name and is preceded by a tilde (~). Like constructors, a
destructor has no return type.

What are the features of a destructor?


The name of the destructor is same as the class name.
The name is preceded by ~.
It is always public.
There is no parameter in the signature.
There is no return type.

When the members of a class are initialized?


If the member variables are not provided with the initial values, then they are assigned default values as
dictated by their types. This is done as follows:
Static variables are initialized to their default values when the class is loaded.
Instance variables are initialized to their default values when an instance of the class is created.
If the variables are provided with the initial values at the time of declaration, then they are assigned as
follows:
Static variables are assigned when the class is loaded.
Instance variables are assigned when an instance is created.
Note: A variable is never “uninitialized”

Is the following statement is correct? Justify your answer.


public static const float PI = 3.14;
The above given statement is wrong and will produce compile-time error. Because all the constant
members are implicitly static, we cannot declare them so explicitly using static.

What is enumeration?
An enumeration (enum) is a value type. It is a special integer data type. The declaration of this data type
defines a type name for a related group of symbolic constants. This data type associates an integral
datatype other than char.
Syntax:
enum identifier[: dataType]
{
enumerator1, enumerator2, … enumeratorN
}
Ex:
enum Vehicle : byte
{
car, bus, van, bike
}

What are the operations not allowed in enum?


1. Adding two enums
2. Subtracting one enum from another enum
3. Comparing two enums

What is the use of this reference?


C# supports the keyword this which is a reference to the object that called the method. The this reference
is available within all the member methods and always refers to the current instance. It is normally used
to distinguish between local and instance variables that have the same name.
Ex:

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 21 Dept. of CSE

class ThisTest
{
int x;
int y;
public ThisTest(int x, int y)
{
this.x = x;
this.y = y;
}
…..
}

Write a note on read‐only members.


The readonly modifier is designed to set the value of the member using a constructor method, but cannot
be modified later. The readonly members can be declared as either static fields or instance fields. When
they are declared as instance fields, they can take different values with different objects.

Differentiate const and readonly members.


const members readonly members
The value must be set when const member is The value of the readonly member is set using a
defined. i.e. compile time constructor method. i.e. runtime
These are implicitly static. These are not implicitly static. These may be
declared as either static fields or instance fields.
Since it is static, It can have only one value and it The instance readonly members can take
is common for all the objects of the class. different values for different objects of the class.

What are accessor and mutator methods? Why we need these methods?
The accessor methods are used to access the data members. And the mutator methods are used to
modify the value of data members.
The object-oriented system will not permit to access the private members directly because of the
implication integrity. The accessor and mutator methods are used for this purpose. They are also called as
getset methods.
Ex:
class TestAccess
{ private int n;
public void SetNumber(int x) //mutator method
{
n = x;
}
public int GetNumber() // accessor method
{
return n;
}
}

What are the demerits of accessor methods?


The programmer has to code the accessor methods manually.
User has to remember that they have to use accessor methods to work with the data members.

What are properties?


Properties have the same capabilities as accessor methods, but are much more elegant and simple to use.
Using a property a programmer can get access to data members easily. These are sometimes referred as
“smart fields”.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 22 Dept. of CSE

Ex:
class TestProp
{
private int n;
public int number //property defines getter and setter methods
{
get
{
return n;
}
set
{
number = value;
}
}
}

What are the powerful features of properties?


Other than fetching the value of a variable, a get clause uses code to calculate the value of the
property using other fields and returns the results. This means that properties are not simply tied
to data members and they can also represent dynamic data.
Like methods, properties are inheritable. The modifiers abstract, virtual, new and override may
be used with them appropriately, so the derived classes can implement their own versions of
properties.
The static modifier can be used to declare properties that belong to the whole class rather than
to a specific instance of the class.

What are indexers?


Indexers are location indicators and are used to access class objects, just like accessing elements in an
array. They are useful in cases where a class is a container for other objects. These are referred as “smart
arrays”.
Ex:
public int this [int index]
{
get
{
//return desired data
}
set
{
//set desired data
}
}

Differentiate indexer from property.


A property can be static member, whereas an indexer is always an instance member
A get acccessor of a property corresponds to a method with no parameters, whereas a get
accessor of an indexer corresponds to a method with the same formal parameter list as the
indexer.
A set accessor of a property corresponds to a method with a single parameter named value,
whereas a set accessor of an indexer corresponds to a method with the same formal parameter
list as the indexer, plus the parameter named value.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 23 Dept. of CSE

It is an error for an indexer to declare a local variable with the same name as an indexer
parameter.
The indexer takes an index argument and looks like array.
The indexer is declared using the name this.

What is the containment inheritance?


If an object contains another object in it, it is called as containment inheritance. This represents the “has-
a” relationship.
Ex:
class A
{
int a;
}
class B
{
int b;
A aa; // object aa is contained in object of B
….
}

What are the constraints on the accessibility of members and classes in C#?
1. The direct base class of a derived class must be at least as accessible as the derived class itself.
2. Accessibility domain of a member is never larger that that of the class containing it.
3. The return type of method must be at least as accessible as the method itself.

What is subclass constructor? How can it be used?


The constructor which is defined in the subclass or derived class of parent class is called as subclass
constructor. It is used to construct the instance variables of both subclass and the superclass.
The subclass constructor uses the keyword base to invoke the superclass constructor.
Ex:
class Point
{ int x;
int y;
public Point(int x, int y) //superclass constructor
{
this.x = x;
this.y = y;
}
}
class ThreeD : Point
{
int z;
public ThreeD(int x, int y, int z) : base (x,y) //subclass constructor
{
this.z = z;
}
}

What are the Characteristics of the Override?


1. An override declaration may include the abstract modifier.
2. It is an error for an override declaration to include new or static or virtual modifier.
3. The overridden base method cannot be static or nonvirtual.
4. The overridden base method cannot be a sealed method.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 24 Dept. of CSE

What is the use of abstract modifier with class?


The abstract is a modifier and when used to declare a class indicates that the class cannot be instantiated.
Only its derived classes can be instantiated. So, the object can’t be created for an abstract class.

What is the use of abstract modifier with methods?


A method declared with abstract modifier is called abstract method. An abstract method is implicitly a
virtual method and does not provide implementation. Therefore, an abstract method does not have
method body.
Ex:
public abstract int Calculate(int x, int y);

What is Characteristic of the Abstract Class?


1. It cannot be instantiated directly.
2. It can have abstract members.
3. We cannot apply a sealed modifier to it.

What is Characteristic of the Abstract Method?


1. It cannot have implementation.
2. Its implementation must be provided in non - abstract derived classes by overriding
the method.
3. It can be declared only in abstract classes.
4. It cannot take either static or virtual modifiers
5. An abstract declaration is permitted to override a virtual method.

What is a sealed class?


A class that cannot be subclassed is called a sealed class. The sealed modifier is used with the class to
create a sealed class. Any attempt to inherit these classes will cause an error and the compiler will not
allow it.
Ex:
sealed class Sample
{
int x;
}
class Test : Sample // compiler will be generated because sample is a sealed class.
{
int y;
}

What is a sealed method?


When an instance method declaration includes the sealed modifier, the method is said to be a sealed
method. It means a derived class cannot override this method.
A sealed method is used to override an inherited virtual method with the same signature. That means, the
sealed modifier is always used in combination with the override modifier.
Ex:
class A
{ int x, y;
public virtual int sum(int x, int y)
{
return (x+y);
}
}
class B : A
{ int z;

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 25 Dept. of CSE

public sealed override int sum(int x, int y, int z)


{
return (x+y+z);
}
}
The sealed method sum overrides the virtual method sum() defined in A. Any derived class of B cannot
further override the method sum().

What is polymorphism? What are the methods available to do that?


Polymorphism means “one name, many forms”. Essentially, polymorphism is the capability of one object
to behave in multiple ways. It can be achieved in two ways:
1. Operation Polymorphism can be achieved by using overloaded methods.
2. Inclusion Polymorphism can be achieved by using virtual methods.

What is operation polymorphism?


Operation polymorphism is implemented using overloaded methods and operators. The overloaded
methods are selected for invoking by matching arguments, in terms of number, type and order. This
information is known to the compiler at the time of compilation and, therefore, the compiler is able to
select and bind the appropriate method to the object for a particular call at compile time itself. This
process is called early binding, or static binding, or static linking. It is also known as compile time
polymorphism.

What is early binding?


Early binding simply means that an object is bound to its method call at compile time.

What is inclusion polymorphism?


Inclusion polymorphism is achieved through the use of virtual functions. The decision on exactly which
method to call is delayed until runtime and, therefore, it is also known as runtime polymorphism. Since
the method is linked with a particular class much later after compilation, this process is termed late
binding. It is also known as dynamic binding because the selection of the appropriate method is done
dynamically at runtime.

Write a note on interface.


An interface can contain one or more methods, properties, indexers, and events but none of them are
implemented in the interface itself. It is the responsibility of the class that implements the interface to
define the code for implementation of these members.
Syntax:
interface InterfaceName
{
Member declarations;
}

What is explicit interface implementation?


The problem of name collision, which may be occur while implementing more than one interface in a
class, can be avoided by using explicit interface implementation.
Ex: interface I1{ int sum(int x, int y); }
interface I2 {int sum (int a, int b); }
class C1 : I1, I2
{ public int sum (int m, int n)
{
return (m+n);
}
}

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 26 Dept. of CSE

Now, the compiler gets confused in selecting the method either from interface I1 or interface I2. But by
using explicit interface implementation this can be avoided.
Ex:
interface I1{ int sum(int x, int y); }
interface I2 {int sum (int a, int b); }
class C1 : I1, I2
{
//explicit interface implementation with no access modifier
int I1.sum (int m, int n)
{
return (m+n);
}
}
Access modifiers are prohibited on explicit interface implementations.

Advantages of explicit interface member implementation


1. Explicit interface member implementation resolves the conflicts of interface members of
different interfaces having same signature.
2. since only the interface instance can access the explicit interface member implementation, the
class or struct that implements this member cannot access this member. Such implementations
are useful when the end-user of the class or struct does not require these members.

What is difference between Classes and Interface?


1. All the members of an interface are implicitly public and abstract.
2. An interface cannot contain fields, constructors and destructors.
3. Its members cannot be declared static.
4. Since the methods in an interface are abstract, they do not include implementation code.
5. An Interface can inherit multiple interfaces.
Class Interface
It encapsulates fields and methods It encapsulates contracts
The methods are implemented Methods should not be implemented
It allows single inheritance It allows multiple inheritance
A class is inheited if there exists a IS A An interface is inherited to implement the methods.
relationship Eventhough there is no IS A relationship, the class is
derived to execute common behaviors.

Can we convert an interface into an equivalent abstract class? Explain with example.
The interfaces are similar to abstract classes. And interfaces can be converted into an abstract class.
Ex:
interface Sample
{
void Print();
int sum(int x, int y);
}
This can be converted into an abstract class as follows:
abstract class Sample
{
abstract public void Print();
abstract public int sum(int x, int y);
}
By default all the members of an interface are public and abstract.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 27 Dept. of CSE

Differentiate Abstract class and Interface


Abstract Class Interface
It is declared with the keyword abstract An interface uses the keyword interface.
It can contain both abstract methods and non- All the methods in an interface are treated
abstract methods. as abstract methods eventhough there is no
abstract keyword in the methods.
Can contain data members, such as variables. Cannot contain data
Requires a common base class to separate Does not require a common base class to
specification from implementation. separate specification from implementation.

What are the operators which can be overloaded?


Binary arithmetic operators +*/-%
Unary arithmetic operators + - ++ --
Binary bitwise operators & | ^ << >>
Unary bitwise operators ~ ! true false
Relational operators == != <= >= > <

What are the operators which can’t be overloaded?


Logical operators && ||
Compound assignment operators += -= *= /= %=
Other operators [] () = ?: -> new sizeof typeof is as

What are limitations of operator overloading?


1. When we overload a binary operator, its compound assignment equivalent is implicitly
overloaded.
2. Relational operators must be overloaded in pairs, i.e == and != must be done together.
3. Operators that are currently not defined in C# cannot be overloaded.
4. We cannot change the syntax, the grammatical rules that govern its use such as the number of
operands, precedence and associativity.

What is need for operator overloading?


1. Mathematical or physical modeling needs classes to represent objects such as coordinates,
vectors, matrices, tensors, complex numbers and so on.
2. Graphical programs where co-ordinate related objects are used to represent positions on the
screen.
3. Financial programs where a class represents an amount of money.
4. Text manipulations where classes are used to represent strings and sentences.

What are the key features of Operator Overloading?


1. They must be defined as public and static
2. The retval (return value) type is the type that we get when we use this operator. But,
technically, it can be of any type.
3. The arglist is the list of arguments passed. The number of arguments will be one for the
unary operators and two for the binary operators.
4. In the case of unary operators, the argument must be the same type as that of the enclosing
class or struct.
5. In the case of binary operators, the first argument must be of the same type as that of the
enclosing class or struct and the second may be of any type.

Define Delegate?
It is an Event handling mechanism of .NET. To raise events, a class must define one delegate per
event type. To handle events, types must implement one event handler per event type. Delegates can
reference both instance and static methods. C# uses the delegate keyword.

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 28 Dept. of CSE

Define Callback method


Method that returns the result of an asynchronous processing call. Most methods are called in a
synchronous fashion in which the call returns only after the result of the call is available. An asynchronous
method call returns prior to the results: Later, a callback method is called to retrieve the result. Also
known as callbacks function in the Win32 API.

What is Abstract class?


A normal, non-abstract class is called a concrete class. An abstract class may contain either or
both abstract and concrete methods. (Properties cannot be marked abstract.) As in ordinary inheritance, a
type derived from an abstract class inherits all the base type members including any method
implementations. But, if any abstract methods are inherited, the class must either declare it abstract or
provide an implementation.
A C# abstract class is declared with the abstract keyword.

What are steps involved in using delegates in a C# program?


1. Delegate declaration
2. Delegate methods definition
3. Delegate instantiation
4. Delegate invocation

Write a note on delegates.


Delegate is a method which is acting for another method. A delegate declaration defines a class using the
class System.Delegate as a base class. Delegate methods are any functions whose signature matches the
delegate signature exactly. The delegate instance holds the reference to delegate methods. The instance
is used to invoke the methods indirectly. An important feature of delegate is that it can be used to hold
reference to a method of any class. The basic requirement is that its signature must match the signature
of the method.

What are delegate multicasting (or) multicast delegates?


The delegate which holds references to invoke multiple methods is called multicast delegates. It is also
known as combinable delegates, must satisfy the following conditions:
The return type of the delegate must be void.
None of the parameters of the delegate type can be declared as output parameters, suing out
keyword.
Ex: MDelegate m3 = m1 + m2;
// m1 and m2 are methods which have the same signature as MDelegate

What is an event?
An event is a delegate type class member that is used by the object or class to provide a notification to
other objects that an event has occurred. The client object can act on an event by adding an event
handler to an event.
The type of an event declaration must be a delegate type and the delegate must be as accessible as the
event itself.

What is the difference between Read() and ReadLine()?


Read( ) - Returns a single character as int. Returns -1 if no more characters are available.
ReadLine() - Returns a string containing a line of text. Returns null if no more lines are available.

What is an error?
Error is a mistake that can make a program go wrong. An error may produce an incorrect output or may
terminate the execution of the program abruptly or even may cause the system to crash. There are two
types of error:
1. Compiler-time errors 2. Run-time errors

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony


Einstein College of Engineering 29 Dept. of CSE

Write some examples for run‐time errors.


1. Dividing an integer by zero
2. Accessing an element that is out of bounds of an array
3. Trying to store a value into an array of an incompatible class or type
4. passing a parameter that is not in a valid range or value for a method
5. Attempting to use a negative size for an array.

What is Exception?
When an unplanned or unexpected event occurs, an associated exception object is thrown. The
exception will be caught by an exception handler at some level and appropriate action taken. A fatal
exception—catastrophic error—is an event that cannot be properly handled to allow the application to
continue.

What is Exception handling?


Process of intercepting—trapping—an exception and acting appropriately in response.

What are tasks involved in exception handling?


1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)

Differentiate Property and Indexer


Property Indexer
A property is identified by its name An indexer is identified by its signature
A property is accessed through the property An indexer element is accessed through the
name subscripted expression with the object name as
the array name.
A property can be static. Indexer is always as instance member

What is Override?
Supercede an instance field or virtual method in a base class with a new definition of that
member in the derived class (subclass).

Common Collections in .NET Framework


Collection Description
ArrayList General purpose, dynamically sized collection
HashTable A collection of associated keys and values that are organized based on the hash
code of the key. Types stored in HashTable should always override
System.Object.GetHashCode().
SortedList Like a dictionary, but the elements can also be accessed by ordinal position (index).
Queue Represents a standard first-in-first-out (FIFO) model
Stack A last-in-firs-out (LIFO) mode that provides push, pop and peek functionality.
BitArray Provides a collection of bit values, where true indicates that the bit is on (1) and
false indicates the bit is off (0).

CS1010 ‐ C# and .NET Framework Two Marks by Roy Antony

You might also like