SHAREPOINT

SHAREPOINT
Spotlight on share server 2010

Tuesday, September 18, 2012


Section – A                                     2 Marks Questions


          [QUESTIONS 1 TO 23]                                 [PAGE 1 TO 4]

 

Q1.      What is c# all about?

Ans.    C# is a new computer programming language developed by Microsoft corporation USA c# is 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 platforms of Microsoft for building component-based software solutions. It is a simple, efficient productive & type-safe language derived from the popular c & c++ languages.

Q2.      What is foreach statement?

Ans.    The foreach statement is similar to the for statement but implemented differently. It enables us to iterate the elements in arrays and collection classes such as list & hash table. The general form of the for each statement is

for each (type variable in expression body of the loop

{

statements…….

}

Here the type & variable declare the iteration variable. During executives, the iteration variable represents the array element for which an iteration is currently being performed in is a key work.

Q3.      What is the use of namespaces in C#?

Ans.    A class in a namespace can be accessed using the dot operator e.g. system. Console. Write line (); Name spaces are the way C# segregates the. NET library classed into reasonable groupings.

C# supports a feature known as using directive that can be used to import the name space system in to the program.

Q4.      What do reference types mean?

Ans.    Reference type can be divided into two groups.

1.    User defined types

2.    Predefined types

User defined: reference types refer to those types, which we define using predefined typed. They include:

Classes

Interfaces

Delegates

Arrays

Predefined reference types includes two data types:

Object type

String type.

Q5.      List the two predefined reference types in C#.

Ans.    The reference types can be divided into two groups

            User defined

                        classes           

                        Interfaces

                        Delegates

                        Arrays

            Predefined

                        Object type

                        String type.

Q6.      Define the term reflection.

Ans.    Reflection is used to get information about a class, method, properties & events. Using reflection we can know the number of methods, events & properties & their syntax.

 

Q7.      Why do we require type conversion?

Ans.    C#  type conversion take place in two ways

1.    Implicit Conversions

2.    Explicit conversions

We often encounter situations where there is a need to convert a data of one type into another before it is used in arithmetic operations or to store a value of one type into a variable of another type, there we need type conversion.        

Q8.      C# is a freeform language. Give Comments.

Ans.    C# is a freeform language. We need not indent any lines to make the program work properly. C# does not care where on the line we begin coding. Although several alternative styles are possible to write codes of C# program.        

            For e.g. the statement

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

                        Can be written as

                                    System.Console.writeLine

                                                (“Hello!”) ;

 

                        Or

                         even as

                                    System.Console.WriteLine

                                                (

                                                “Hello!”

                                                )

                                                ;          

Q9.      What do you understand by Lexical structure?


Ans.    Every C# statement comes under Lexical structure for e.g. Operators, control statements etc.

Q10.    Explain application of C#.

Ans.    C# is a new language developed exclusively to work on .NET platform. It can be used for variety of applications that are supported by the .NET platform:

Ø  Console applications

Ø  Windows applications

1.            Developing windows controls

2.            Developing ASP.NET projects.

3.            Creating web controls

4.            Providing web services.

5.            Developing .NET Component library.

Q11.    C# modernizes C++ by adding the features. Explain.

Ans.    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 & events

6.            Boxing & Unboxing

7.            Web services.

Q12.    Define OLE Technology.

Ans.    OLE (Object Linking & Embedding) technology was developed by Microsoft in the early 1990s to enable easy inter process communications. OLE provided support to achieve the following.

1.   To embed documents from one application into another application

2.    To enable one application to manipulate objects located in another applications.

This enables users to develop applications, which required inter-operability between various products such as Ms Word & MS Excel.

Q13.    Define .NET Technology.

Ans.    .NET Technology is a third-generation component model. This provides a new level of inter-operability compared to COM technology. COM provides a standard binary mechanism for inter-module communication. This mechanism is replaced by an intermediate language called Microsoft inter media language (MSIL) or simply IL in the .NET technology.

Q14.    Define COM technology.

Ans.    COM stands for component object model. In the component-based approach a program is broken in to a number of independent components where each one offers a particular service. Each component can be developed & tested independently & the integrated it into main system. Com technology offers a number of benefits to developers & users. It

1.    reduces the overall Complexity of software.

2.    enables distributed development across multiple organizations or departments and

3.    Enhances software maintainability.

Q15.    What is CLR?


Ans.    CLR is common language Runtime. CLR is heart & soul of the .NET framework. CLR is runtime environment in which programs written in C# and other .NET languages are executed. It also supports cross language interoperability.

Q16.    What are the services provided by CLR?

Ans.    There are various types of services provided by the CLR. Those are used to execute and compile a .NET program efficiently.

            1.   Loading & execution of programs

            2.   Memory isolation for application

            3.   Verification of type safety.

4.    Computation of IL into native executable code.

5.    Providing Metadata.

6.    Memory management

7.    Enforcement of security

8.    Interoperability with other systems.

9.    Managing exceptions & errors

10.  Support for tasks such as debugging & profiling.

Q17.    Define comments in C#.

Ans.    Comments are used to enhance readability & understanding of the code. C# support two types of comments.

1.            Single Line Comments (//)

2.            Multi Line Comments (/*-----

                                               -----*/)  

Q18.    How we can use more than one Main method in C#?


Ans.    C# includes a feature that enables us to define more than one class with the Main method. Since Main is the entry point for execution, there are now more than one entry points. In fact, there should be only one. This problem can be resolved by specifying which Main is to be used to the computer at the time of compilation as shown below.

            csc filename  /main:classname

Q19.    Define C# program structure.

Ans.    C# program is the divided into the following section. That describe the structure of the c program.

Documentation section
Using Directive Section
Interfaces section
Classes section
Main method section

Optional

Optional

Optional

Optional

Essential

 

Q20.    What are the various looping statements in C#?

Ans.    1.         The while statement

            2.         The do statement

3.            The for statement

4.            The for each statement.

Q21.    What is the scope of variables?

Ans.    The scope of a variable is the region of code within which the variable can be accessed. This depends on the type of the variable & place of its declaration. C# defines several categories of variables. They include

 

·         Static variables

·         Instance variables

·         Array variables

·         Value parameters

·         Reference parameters

·         Local variables

Q22.    Define Constants.

Ans.    A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies. The example

 

               class Constants  
               {  
                  public const int A = 1;  
                  public const int B = A + 1;  
               }  

shows a class named Constants that has two public constants.

Q23.    What is boxing & unboxing?

Ans.    Boxing:

 Any type, value or reference can be explicitly converted. When the compiler finds a valued type where it needs a reference type, it creates an object “box” into which it places the value and converts it into the object type. This process is called boxing.

UNBOXING: 


Unboxing is the process of converting the object type back to the value type. Remember that we can only unbox a variable that has previously been boxed. In contrast to boxing, unboxing is an explicit operation.


Section – A                                     5 Marks Questions


          [QUESTIONS 1 TO 21]                              [PAGE 5 TO 16]

 

 

Q1.      How C# better than java explain?


Ans.    C# provided some new features that are not available in java that makes it better than java. These features are as follows.

1.    C# has more primitive data types

2.    Unlike java, all c# data types are objects.

3.    Java does not provide for operator overloading.

4.    C# checks overflows using checked statements.

5.    C# allows a variable number of parameters using the params keyword.

6.    C# includes native support for properties java does not

7.    C# provides better versioning support than java.

8.    C# provides built in delegates & events.

Q2.      State at least eight important highlights of C# language.

Ans.

1.    Simple:

C# simplifies C++ by eliminating irksome operators such as ->,: and pointers. C# treats integer and Boolean data types as two entirely different types. This means that the use of = in place of = = in if statements will be caught by the compiler.

2.    Consistent:

C# supports and unified type system which eliminates the problem of varying ranges of integer types. All types are treated as objects and developers can extend the type system simply and easily.

            3.    Modern:

C# is called a modern language due to number of features it supports.  It supports

·       Automatic garbage collection

·       Rich intrinsic model for error handling

·       Decimal data type for financial applications

·       Modern approach to debugging and

·       Robust security model

      4.    Object-oriented

C# is truly object-oriented. It supports all the three tenets of object-oriented systems, namely.

·         Encapsulation

·         Inheritance and

·         Polymorphism

The entire C# class model is built on top of the Virtual Objects System (VOS) of the .NET framework. In C#, everything is not object. There are no more global functions, variables and constants.

            5.    Type-safe

Type-safety promotes robust programs. C# incorporates a number of type-safe measures.         

·         All dynamically allocated objects and arrays are initialized to zero.

·         Use of any un-initialized variables produces an error message by the compiler.

·         Access to arrays are range-checked and warned if it goes out-of-bounds

·         C# does not permit unsafe casts

·         C# enforces overflow checking in arithmetic operation.

·         Reference parameters that are passed are type-safe

·         C# supports automatic garbage collection

 

            6.   Version-able:

Making new versions of software modules work with the existing applications is known as versioning C# provides support for versioning with the help of new override keywords. With this support, a programmer can guarantee that his new class library will maintain binary compatibility with the existing client applications.

7.     Compatible:

C# enforces the .NET common language specification and therefore allows inter-operation with other. NET languages.

C# provides support for transparent access to standard COM and OLE Automation.

C# also permits interoperation with C-style APIs.

8.     Flexible:

Although C# does not support pointers, we may declare certain classes and methods as ‘unsafe’ and then use pointers to manipulate them. However, these codes will not be type-safe.

Q3.      What are the various control statements available in C#? Discuss them.

Ans.    C# support following control statements:-

            Decision making with if Statement

The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is a two-way decision statement and is used in conjunction with an expression. It takes the following form:

 

      If (expression)

 

 
Expression
         ?

Entry

True

False
 


 

 

 

 

 

 

 

 

 

 

 


           

            Simple If Statement

      The general form of a simple if statement is

      If (Boolean-expression

      {

                  statement-block;

      }

                  statement –x;

 

The Switch statement

We have seen that when one of many alternatives has to be selected, we can design a program using if statements to control the selection. However, the complexity of such a program increased dramatically when the alternatives increase. The program becomes difficult to read and follow. At times, it may confuse even the designer of the program. Fortunately, C# has a built-in multi way decision statement known as a switch. The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below.

 

                        switch (expression)

            {

            case value –1:

                     block –1

                     break;

              case value-2:

                   block-2

                      break;

                                     

                   Default:

                        Default-block

                        Break:

            }

            statement-x:   

            The? : Operator

C# has an unusual operator, useful for making two –way decisions; it is a combination of? and, and takes three operands. This operator is popularly known as the conditional operator. The general form of use of the conditional operator is as follows:

conditional expression? expression 1: expression2

Q4.      How is C sharp is different from C++?

Ans.    C# eliminates preprocessor macros.

·         The variables in C# have to be initialized before they are referenced

·         Arrays are defined in a much simpler manner in C#.

·         C# prohibits pointers. Instead objects are manipulated strictly via reference.

·         Inheritance is limited to encourage the development of good class hierarchies.

Q5.      State features of C++ that have not been incorporated into C#.

Ans.    The following C++ features are missing from C#.

            Macros

            Multiple inheritance

            Templates

            Pointers

            Global variables

            Typedef statement

            Default arguments

            Constant member functions or parameters Forward declaration of classes.

Q6.      Discuss the coding style in C sharp.

            Or

            C# is a free form language. Give comments.

Ans.    C# is a freeform language. We need not indent any lines to make the program work properly. C# does not care where on the line we begin coding. While this may be a license for bad programming, we should try to use this fact to our advantage of designing readable programs. Although several alternative styles are possible, we should select one & try to use it consistently.

            For eg., the statement

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

                        Can be written as

                                    System.Console.writeLine

                                                ( “Hello !”) ;

                        Or , even as

                                    System.Console.WriteLine

                                                (

                                                “Hello!”

                                                );

Q7.      Write a program in C# to find the smallest number among five numbers.

Ans.    using system;

            class M

            {

            public static void Main()

            {

            int i = 1;

            int n ; small=32767;

            while (I<=5)

            {

            n = int.Parse (Console.ReadLine ());

            if (n

            small = n

            }

            Console.WriteLine (“smallest no” + small);

            }

            }

Q8.      What are the features of C# and java that both shares?

Ans.    Below is a list of features C# and Java share, which are intended to improve on C++. These features are not the focus of this article, but it is very important to be aware of the similarities.

·         Compiles into machine-independent language-independent code which runs in a managed execution environment.

·         Garbage Collection coupled with the elimination of pointers (in C# restricted use is permitted within code marked unsafe)

·         Powerful reflection capabilities

·         No header files, all code scoped to packages or assemblies, no problems declaring one class before another with circular dependencies

·         Classes all descend from object and must be allocated on the heap with new keyword

·         Thread support by putting a lock on objects when entering code marked as locked/synchronized

·         Interfaces, with multiple-inheritance of interfaces, single inheritance of implementations

·         Inner classes

·         No concept of inheriting a class with a specified access level

·         No global functions or constants, everything belongs to a class

·         Arrays and strings with lengths built-in and bounds checking

·         The "." operator is always used, no more ->, :: operators

·         null and boolean/bool are keywords

·         All values are initialized before use

·         Can't use integers to govern if statements

Q9.      How we can Pass and Return Parameters to main?


Ans.    If you wish to pass in parameters from the command-line to your program, you should use the following form that takes an array of command-line arguments.

public static void Main( string[] args )
{
  . . .
}

You can then use the args.Length parameter to check if an argument has been passed in or not.

Returning Parameters


Applications return the value zero when everything is running normally. However we can use this ability to return a value other than zero for error purposes. If you were to run an application from a batch file, error codes could be returned in this manner and acted upon as needs be.

public static int Main()
{
  . . .
  
return 0;
}

Passing and Returning Parameters


We can combine the previous two formats into one using the following:

public static int Main( string[] args )
{
  . . .
  
return 0;
}

So that's it, the four different types of declaration for the Main method.

Q10.    Define Looping Statements in detail..

Ans.    C# provide different types of loops to execute loop process. It is the process to execute certain set of code repeatedly.

1.    while loop :- Taken from the tradition language have same syntax as it is in the ‘c’ or ’c++’.

Syntax

while(expression)

{

statements;

}

2.    do while loop:-use to execute code again and again till the criteria matches.

Define with the following syntax

do

 {

statements;

 } while(expression);

in this loop process condition check after the statement executes.

                 

3.   for / foreach Statements

In for loop the expression, initialization and step value for the loop variable can define with in the single pair of parenthesis. It has the following syntax.

 

 for(initialization; expression; step value)

     {     

……………

     }

 

4. foreach statements is the newer statement in c#. Commonly used with reference types of data or collection to get data one by one. This loop can execute with following syntax.

foreach (int i in IntList)

{

...

}

Note: Generally use brackets even if there is only one statement in the loop.

Q11.    Define Predefined Data Types in C#.

Ans.    C# provides a set of predefined types, most of which will be familiar to C and C++ developers. The predefined reference types are object and string. The type object is the ultimate base type of all other types. The type string is used to represent Unicode string values. Values of type string are immutable. The predefined value types include signed and unsigned integral types, floating-point types, and the types bool, char, and decimal. The signed integral types are sbyte, short, int, and long; the unsigned integral types are byte, ushort, uint, and ulong; and the floating-point types are float and double. The bool type is used to represent boolean values: values that are either true or false. The inclusion of bool makes it easier to write self-documenting code, and also helps eliminate the all-too-common C++ coding error in which a developer mistakenly uses "=" when "==" should have been used. The table below lists the predefined types, and shows how to write literal values for each of them.

Type
Description
Example
Object
The ultimate base type of all other types
object o = null;
String
String type; a string is a sequence of Unicode characters
string s = "hello";
Sbyte
8-bit signed integral type
sbyte val = 12;
Short
16-bit signed integral type
short val = 12;
Int
32-bit signed integral type
int val = 12;
Long
64-bit signed integral type
long val1 = 12;
long val2 = 34L;
Byte
8-bit unsigned integral type
byte val1 = 12;
Ushort
16-bit unsigned integral type
ushort val1 = 12;
Uint
32-bit unsigned integral type
uint val1 = 12;
uint val2 = 34U;
Ulong
64-bit unsigned integral type
ulong val1 = 12;
ulong val2 = 34U;
ulong val3 = 56L;
ulong val4 = 78UL;
Float
Single-precision floating point type
float val = 1.23F;
Double
Double-precision floating point type
double val1 = 1.23;
double val2 = 4.56D;
Bool
Boolean type; a bool value is either true or false
bool val1 = true;
bool val2 = false;
Char
Character type; a char value is a Unicode character
char val = 'h';
decimal
Precise decimal type with 28 significant digits
decimal val = 1.23M;

 

Q12.    Define Operators and their types.

Ans.    Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands.  Examples of operators include +, -, *, /, and new.  Examples of operands include literals, fields, local variables, and expressions. There are three kinds of operators:

·         Unary operators.  The unary operators take one operand and use either prefix notation (such as -x) or postfix notation (such as x++).

·         Binary operators.  The binary operators take two operands and all use infix notation (such as x + y).

·         Ternary operator.  Only one ternary operator, ?:, exists; it takes three operands and uses infix notation (c ? x : y).

Q13.    Define precedence of operators in term of coding.

Ans.    When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. [Note: For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the binary + operator.] The following table summarizes all operators in order of precedence from highest to lowest:

 

Category
Operators
Primary
x.y f(x) [x] x++ x-- new
typeof checked unchecked
Unary
+ - ! ~ ++x --x (T)x
Multiplicative
* / %
Additive
+ -
Shift
<< >>
Relational and
type-testing
< > <= >= is as
Equality
== !=
Logical AND
&
Logical XOR
^
Logical OR
|
Conditional AND
&&
Conditional OR
||
Conditional
?:
Assignment
= *= /= %= +-= -= <<= >>= &= ^= |=

 

Operator associativity

When an operand occurs between two operators with the same precedence, the associativity of the operators controls the order in which the operations are performed:

·         Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. [Example: For example, x + y + z is evaluated as (x + y) + z. end example]

·         The assignment operators and the conditional operator (?:) are right-associative, meaning that operations are performed from right to left. [Example: For example, x = y = z is evaluated as x = (y = z). end example]

Precedence and associativity can be controlled using parentheses. [Example: For example, x + y * z first multiplies y by z and then adds the result to x, but (x + y) * z first adds x and y and then multiplies the result by z. end example]

Q14.    Define command line arguments.

Ans.    There may be occasions when we may like our program to behave in a particular way depending on the input provided at the time of execution. This can be achieved by command line arguments in c#. Command line arguments are parameters supplied to the Main method at the time of invoking it for execution. E.g

using System;

class Sample

{

            public static void Main (string [] args)

{

            Console.Write(“Welcome to “);

            Console.Write(“  “+args[0]);

            Console.WriteLine(“ “+args[1]);

            }

}

Q15.    Define compile time errors.

Ans.    A program may contain two types of errors

·         Syntax Errors

·         Logic Errors

Syntax errors are generated by the compiler, if any mistake in the code syntax and remove by writing accurate syntax. Logical errors are removed by testing the program logic carefully.

When the compiler cannot interpret what we are attempting to convey through our code the result is syntax error. In such situations the compiler will detect the error and display the appropriate error messages. This error is called compile time error.

 

For example.

using System;

class SampleTen

{

            public static void main()

            {

                        Console.WriteLine(“Hello, Errors”)

            }

}

In this program the main function generate a compile time error. Because it is not defined with capital “M”.

Q16.    Define literals in detail.

Ans.    Literals are value constants assigned to variables (or results of expressions) in a program. C# supports several types of literals as

 

Numeric Literals

C# Literals

Boolean Values

Character Literals

String Literals

Single Character
Literals

Real Literals

Integer Literals
 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Integer Literals:- An Integer Literal refers to a sequence of digits. There are two types of integers, namely decimal integer and hexadecimal integers.

Decimal integer consists of a set of digits, 0 through 9, preceded by an optional minus sign. Valid examples of integer literal are

123 –321 0 654321

example of hex integers are: 0x2 0x9f 0xbcd 0x

Real Literals: Integer literals are inadequate to represent quantities that vary continuously such as distances, height temperatures, process and so on. Numbers containing fractional literals like 17.528 represents these quantities. Such numbers are called real numbers.  Examples are 0.0083 –0.75 435.36

These numbers are shown in decimal notations as 218. .95 -.71 are valid real literals.

 

 

Boolean Literals:- There are two Boolean literal values:

·         True

·         False

They are used as values of relational expressions

Single Character Literals:- A single character literal contains a single character enclosed within a pair of single quote marks. Example of character in the above constant are: ‘5’ ‘x’


String Literals:- A string literal in a sequence of character enclosed between double quotes. The characters may be alphabets, digits, special character and blank spaces.

Example Hello c#” “2001” “5+3” etc.

Backlash Character Literal:- C# supports some special backslash character constants that are used in output methods. For example the symbol ‘\n’ stands for a new line character, although they consist of two characters. These character combinations are known as escape sequence.

 


Backslash character Literals


Constants
Meaning
‘\a’
alert
‘\b’
Back space
‘\f’
Form feed
‘\n’
New-line
‘\r’
Carriage return
‘\t’
Horizontal tab
‘\v’
Vertical tab
‘\’’
Single quote
‘\”’
Double quote
‘\\’
Backslash
‘\o’
Null

 

Q17.    What do you mean by scope of variables discuss in detail?

Ans.    The scope of a variable is the region of code within which the variable can be accessed. This depends on the type of the variable & place of its declaration. C# defines several categories of variables. They include

·         Static variables

·         Instance variables

·         Array variables

·         Value parameters

·         Reference parameters

·         Local variables

 

            Consider the following example

            class abc

            {

            static int m;

            int n;

            void fun(int x, ref int y, out int z, int [] a)

            {

            int j=10;

            ………

            ……..

            }

            }

           

 

            This code contains the following variables

·         m as static variable

·         n as an instance variable

·         y as a reference parameter

·         x as value parameter

·         z as an output parameter

·         a[0] as an array element

·         j as local variable

Static and instance variables are declared at the class level and are known as a fields or class variable. The scope of these variables begins at the place of their declaration and ends when the Main method terminates.

The variable x, y, z are parameters of the method fun(). The value parameter x will exit till the end of the method. The reference and output parameter ( y and z) do not create new storage locations. Instead they represent the same storage location as the variables that are passed as arguments. The scope of these variables is always the same as underlying variables.

The elements of an array such as a[0] come into existence when an array instance is created, and cease to exist when there are no references to that array instance. Array declared at class level behave like fields.

Local Variables

Variables are declared inside methods are called local variables. They are called as local because they are not available for use outside the method definition.

Q18.    Define conversions and explain its types.

Ans.    The predefined types also have predefined conversions. For instance, conversions exist between the predefined types int and long. C# differentiates between two kinds of conversions:

            implicit conversions and explicit conversions. Implicit conversions are supplied for conversions that can safely be performed without any additional security. That is the conversion can always be performed without any loss of data.  For instance, the conversion from int to long is an implicit conversion. This conversion always succeeds, and never results in a loss of information. The following example

            using System;  
            class Test  
            {  
             static void Main() {  
            int intValue = 123;  
            long longValue = intValue;  
            Console.WriteLine("{0}, {1}", intValue, longValue);  
            }  
            }  

implicitly converts an int to a long.

In contrast, explicit conversions are performed with a cast expression. This  example  shows the implementatuib of explicit conversion.

            using System;  
            class Test  {  
            static void Main() {  
            long longValue = Int64.MaxValue;  
            int intValue = (int) longValue;  
            Console.WriteLine("(int) {0} = {1}", longValue, intValue);  
            }                 }  

            uses an explicit conversion to convert a long to an int. The output is:

            (int) 9223372036854775807 = -1  

because an overflow occurs. Cast expressions permit the use of both implicit and explicit conversions.

Q19.    Write down all the functions provided by math class.

Ans.    The System namespace defines a class known as Math class with a rich set of static methods that makes math-oriented programming easy and efficient. It also contains two static members, E and PI.

            Following are the methods provided by Math class.

Methods
Description
Sin()
Sine of an angle in radians
Cos()
Cosine of an angle in radians
Tan()
Tangent of an angle in radians
Asin()
Inverse of sine
Acos()
Inverse of cosine
Atan()
Inverse of tangent
Sqrt()
Square root
Pow()
Number raised to a given power
Exp()
Exponential
Log()
Natural logarithm
Log10()
Base 10 logarithm
Abs()
Absolute value of number
Min()
Lower of two number
Max()
Higher of two numbers
Sign()
Sing of the number

 

Q20.    WAP to find the value of a specified sin and cos theta.

Ans.    using System;            

            class Mt

            {

            public static void Main()

{
double s,r,r1;

Console.WriteLine(“Enter theta ”);

s=double.Parse(Console.ReadLine());

 r=Math.Sin(s*Math.PI/100);

Console.WriteLine(“value for “+s +”sine theta is “ + r);

r1=Math.Cos(s*Math.PI/100);

Console.WriteLine(“value for “+s +”cos theta is “ + r1);

}
}

Q21.    What are jumping statements used in c#? Explain with example.        

Ans.    Loop perform a set of operations repeatedly until the control variable fails to satisfy the test condition. But there are some statements those are used to jumps out of from the loop process these statements are called jumping statements.

1.    break :- When a break statement is encountered inside a loop, the loop is exited and the program continues with statement immediately following the loop.

Syntax:

break;

2. continue:-    Like the break statement, c# supports another statement called the continue statement called the continue statement. The continue statement, as the name implies, causes the loop to continue with the next iteration after skipping any statements in between. The continue statement tells the complier . “SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.

Syntax:

            Continue;

 

 

Following program show you the use of break and continue

using System;

class con

{

public static void Main()

{
int n=10;

while(n<200 o:p="o:p">

{
if(n<50 o:p="o:p">

{

Console.Write(“ “+n);

n=n+5;

continue;

}

if (n==50)

{

Console.WriteLine();

n=n+5;

continue;

}

if(n==90)

break;

n=n+10;

}
}

}


Section – B                                     2 Marks Questions


          [QUESTIONS 1 TO 26]                              [PAGE 17 TO 20]

 

Q1.      Define main() method.

Ans.    In every executable c# program main is defined. This is the entry point for execution in c# program. A c# program can have any number classes but only one class have a Main() method to Initiate the execution.

Q2.      How to declare method in c#?

Ans.    Methods are declared inside the body of the class, normally after the declaration of data fields. The general form of a method declaration is

            Modifiers  type method name (formal parameter)

{
body

            }

Q3.      What do you mean by modifiers?

Ans.    The modifiers specify keywords that decide the nature of accessibility and the mode of application of the method. A method can take one or more of the modifier. Some of the modifiers are

            “new “- use to hide an inherited method with the same signature

            “public”- to make method accessible any where.

“protected “ - The method can be accessed from within the class to which it belongs, or a type derived 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.

Q4.      What are the value parameters? When do we use them?

Ans.    Parameters declared with no modifier are called value 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 parameter within the body of the method. This is because the methods refer to only copies of those variable when they are passed by value.

Q5.      Define reference parameter with methods in c#.

Ans.    In pass by reference parameter we can force the value parameters to be passed by reference. To do this, we use the ref key word. A parameter declared with the ref modifier is a reference parameter.

            e.g.      void modify (ref int x) Here, x is declared as a reference parameter.

A reference parameter does not create a new storage location. If represents the same storage location as the actual parameter used in the method invocation. Reference parameters are used in situations where we would like to change the values of variable in the calling method.   

Q6.      Define out parameters.

Ans.    Output parameters are used to pass result back to the calling method. This is achieved by declaring the parameters with an out keyword. Similar to the 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 format parameter is declared as out the corresponding actual parameter in the calling method must also be declared as out e.g.

void output (out int x)

{   x = 100 ; 

                   }

---------------

---------------

int m;

Output (out m);

Q7.      How to write a method that accepts a variable number of parameters?

Ans.    In C# we can define methods that can handle variable number of arguments using what are known as parameter arrays. Parameter arrays are declared using the keyword parameters. e.g.,

            void function1 (params int[] x)

            2

            --------

            -------

            3

            Here the x has been declared as a parameter array. The parameter arrays must be one dimensional arrays. A parameter may be a part of a formal parameter list and in such cases, it must be the last parameter.

Q8.      What is use of Extern keyword with method definition?

Ans.    If extern keyword is defined with method definition then the method is implemented externally in different languages..

Q9.      Define array and their use.

Ans.    Arrays are group of elements having same name, same type with contiguous memory locations. Arrays are declared because it is write process to handle a situation in which we have to declare number of variables having same types, instead of declaring different variable, a single array variable can declare.

Q10.    How many types of array we can declare in c#?

Ans.    The following types of array we can declare in c#

            1. Single Dimension

            2. Multi Dimension

            3. Jagged Array / Variable Length array       

Q11.    How the single Dimension Array can declare?


Ans.    Following syntax is used to declare single dimension array. And it can either move towards rows or columns.

            Syntax

datatype[] variable=new datatype[size];

e.g       int[] i = new int[100];

            to initialize the single dimension array the following syntax is used.

            Syntax

            Datatype []variable=new datatype[size]{value1,value2,…..};

            e.g  int[] i=new int[]{3,4,5,6,7};

Q12.    Write down the syntax to declare or initialize the double dimension array.

Ans.    To declare double dimension array following syntax is used.

            Syntax

            Datatype [ , ]variable=new datatype[rows,cols];

            e.g  int[ , ] x=new int[2,3];

            to initialize double dimension array following syntax is used.

            Datatype [ , ] variable=new datatype[ , ]{value1,value2,value3};

            e.g  int[ , ] x=new datatype[ , ]{{1,2},{3,4}};

Q13.    Define jagged array and its declaration.

Ans.    Using jagged arrays, one can create multidimensional arrays with irregular dimensions. This flexibility derives from the fact that multidimensional arrays are implemented as arrays of arrays.

            Syntax

            datatype[][] variable=new datatype[size][];

            e.g

            int [][] x=new int[2][];

Q14.    How jagged array can initialized in c#?


Ans.    The following syntax is used to initialize the jagged array.

            Syntax

            Dataype[][] variable=new int[]{new int[]{1,2,3,4}, new int[]{5,6,7,8,9}};

Q15.    Define StringBuilder class.

Ans.    Mutable strings that are modifiable can be created using the StringBuilder class. Mutable strings are also known dynamic strings.

            E.g.

            StringBuilder str1=new StringBuilder (“abc”);

            StringBuilder str2 = new StringBuilder ();

Q16.    What do you mean by sorting?


Ans.    Sorting is the process to arrange data in a specific order, so that searching process become easy and less time consuming. There are different types of techniques, used to sort data.

1.    Merge sort  2. Bubble sort  3. Insertion sort  etc.

Q17.    What are smart arrays?

Ans.    Smart arrays are variable length array. Their size can be increase or decrease during execution of the program. They are also called Dense/jagged array.

Q18.    When do we prefer the use of structs over classes?


Ans.    Structs are similar to classes in C#. Although classes will be used to implement most objects, it is desirable to use structs where simple composite data types required. Because they are value types stored on the stack, they have the following advantages compared to class objects stored on the heap.

            They are created much more quickly than heap-allocated types.

            They are instantly & automatically deallocated once they go out of scope

            It is easy to copy value type variable on the stack.

            The performance of programs may be enhanced by judicious case of structs.

Q19.    How to initialize a string in c#?

Ans.    Following steps are used to initialize string in c#.          

1      Type tring str where str is the name of the variable to hold the string.

2      Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1.

3      Type ; (a semicolon) to end the statement

Q20.    How the length of string we can find?

Ans.    To find the length of string Length property is used.

            e.g

            string str=”raman”;

            int l;

            l=str.Length;

            Console.WriteLine(“Length of string is “+l);

Q21.    How two strings are concatenated in c#?

Ans.    To concatenate strings in c#, two operator ‘+’ and ‘+=’ are used. We can concatenate string using  System.String.Concat() method also.

e.g       string s1=”welcome”;

                        string s2=”to”;

string s3=”you”;

                        System.String.Concat(s1,s2);

                        s1+=s3;

                        System.Console.WriteLine(“After Concatenation “ + s1);

Q22.    What is the use of IndexOf() and LastIndexOf() method with string in c#?

Ans.    The IndexOf() method is used to find the occurrence of a specified character with in a string from beginning where as LastIndexOf() method find the last occurrence of a specified character with in a string

Q23.    How the part of string we can extract from a string?

Ans.    To extract a part of a string from a string “substring” method is used. It has following syntax.        

            string substring(index1,length);

e.g       string str=”welcome to patiala”;

            string s=str.Substring(11,7);

Q24.    What is the use of split method with string in c#?

Ans.    Split method of string class split the string into different parts those comes before and after the specified delimeter or symbol.

e.g.

            string str=”first, second, third, fourth”;

            string []str1=str.Split(‘,’);

Q25.    What is the use of join method in c#?

Ans.    System.String.Join() method is used to join an array of strings to make single string with specified delimeters. Following syntax is applied with join method.

            Syntax.

             string  System.String.Join(‘delemeter’,array of string);

            e.g

            string []str=new string[3]{“rajesh”,”karan”,”aman”};

string str1=System.String.Join(‘,’,str);

Q26.    How a string is converted in upper case from lowercase and in lowercase from uppercase?

Ans.    ToUpper() and ToLower() method of string class are used to convert from lower to upper and upper to lower a string.

            e.g

            string str=”ravi”;

            str.ToUpper();

            string str1=”Rajesh”;

            str1.ToLower();

 

 


 

 

Section – B                                     5 Marks Questions


          [QUESTIONS 1 TO 21]                              [PAGE 20 TO 29]

 

Q1.      Distinguish between ref and out parameters with example.

Ans.    In c# there are different types of parameters used with methods.

1.    value 2. ref 3. out 4. params

            Both parameters have their specific benefits.

            Difference between ref and out parameters

 

Reference parameters
Output parameters
Define with ref keyword
Define with out keyword
Can access the address of the reference variable and value modifies onto the specific address
Using this parameter an output variable is passed to method we can not use it for the input purpose and it will return the value of the calling method.

 

            The following example will show you the use of ref parameter

            Using System;

            Class PassByRef

            {

            static void swap(ref int x, ref int y)

            {
int temp=x;

            x=y;

            y=temp;

            }

            public static void main()   {

            int m=100;

            int n=200;

            Console.WriteLine(“Before Swapping”);

            Console.WriteLine(“m=”+m);

            Console.WriteLine(“n=”+n);

            swap(ref m,ref n);

            Console.WriteLine(“After swapping “);

            Console.WriteLine(“m=”+m);

            Console.WriteLine(“n=”+n); 

            }  }

 

Following example will show u the benefit of output parameters

            using System;

            class output

            {

            static void square(int x,out int y)

            {
y=x*x;

                        }

            public static void Main()

            {
int m;

            square(10,out m);

            Console.WriteLine(“m=”+m);

                        }

            }

Q2.      What is an array? Write a C# program to implement two-dimensional array.

Ans.    An array is a group of contiguous or related data items that share a common name.

            They are of following types

1.    Single Dimension

2.    Two Dimension

            two dimension array are used where table of value to be stored.

            The following program will show the implementation of two dimension array

            using System;

            class multable  {

            static in ROWS=20;

            static in COLUMNS=20;

            public static void main()  {

            int[,] product=new int[ROWS,COLUMNS];

            int row, column;

            Console.WriteLine(“Multiplication Table”);

            Console.WriteLine(“ “);

            int i,j;

            for(i=10;i

             {

            for(j=10;j

            {
product[i,j]=i*j;

            Console.Write(“   “+product[I,j]);

            }

            Console.WriteLine( “ “);

            }

}
}

Q3.      Create a program using array list class.

Ans.    Array List class:

            using System;

            using System. Collections;

            class City

            {

                  public static void main () 

                              {

                              ArrayList n = new ArrayList ();

                              n. Add (“VIRK P.S.”);

                              n. Add (‘Patiala”);

                              n. Add (“9815665189”);

                              Console.WriteLine (“capacity = “ +n.capacity);

                              Console.WriteLine (“elements present = “+n. Count);

                              n.Sort ();

                              for (int I =0; I

                              {

                                    Console.WriteLine (n Ci]);

                              }

                              Console.WriteLine ();

                              n. RemoveAT (2);

                              for (int I=0; I< =n. Count; I++)

                             

                              {

                              Console.WriteLine (n[I]);

                                    }

                                 }             

                              }

Q4.      WAP to initialize a struct using parameterized constructor.

Ans.     using System;
             public struct Point 
               {
                  public int x, y;
                  public Point(int p1, int p2) 
               {
                  x = p1;
                  y = p2;    
               }
               }
               class MainClass 
               {
               public static void Main()  
               {
               Point myPoint = new Point();
               Point yourPoint = new Point(10,10);
               Console.Write("My Point:   ");
               Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);
               Console.Write("Your Point: ");
               Console.WriteLine("x = {0}, y = {1}", yourPoint.x, yourPoint.y);
               }
               }

Q5.      Define Enumerations.

Ans.    An Enumerations is a user-defined integer type which provides a way for attaching name to numbers, thereby increasing the comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2 and so on. This facility provides an alternative means of creating ‘constant’ variable names. The syntax of an enum statement is illustrated below.

Example

Enum Shape

{

            Circle,

            Square,

            Triangle

}

This can be written as enum shape{Circle, Square, Triangle}

Q6.      Define Structures.

Ans.    Structures are similar to classes in C#. although classes will be used to implement most objects, it is desirable to use structs where simple composite data types are required. Because they are values types stored on the stack, they have the following advantages compared to class objects stored on the heap:

            They are created mush 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.

The performance of programs may be enhanced by judicious use of structs.

Following syntax is used to define struct

Struct structname

{

struct-members;

struct-members;

}

using the following syntax we can declare structure variable.

structname variablename.

Q7.      (a) Distinguish between string and string builder classes.

Ans.    String Class: String is the predefined reference type we can string to declare string type objects. This class is available in System namespace.

StringBuilder:  Mutable strings that are modifiable can be created using the StringBuilder class. Mutable strings are also  known dynamic strings.

            E.g.

            StringBuilder str1=new StringBuilder (“abc”);

            StringBuilder str2 = new StringBuilder ();

            There are following differences between string and stringBuilder classes

 

String
StringBuilder
Create store any string type value the string class is used
String builder class create a mutable string that can modify
Following methods are not available in string
Append(), appendFormat(), EnsureCapacity(), Insert()
Remove(), replace()
All these method are available in this class

 

(b)       What is concatenation? How is it achieved in c#?

Ans.    Concatenation is the process to concatenate two string . we can achieve that in c# with “+” operator and  concat() function

            e.g

            string s1=”welcome”;

            string s2=”bye bye”;

            string s3=s1+s2;

Q8.      Design structure data type:


(a)  Named date of birth to contain date, month, and year of birth. Develop a c# program using this structure that would assign your date of birth to the individual members and display the date of birth in the following format:

(b)  Modify the above program using a constructor to input values to the individual members

Ans.    (a)

            struct dob

            {
int dd,mm,yy;

            public void setval(int dd,int mm,int yy)

            {
this.dd=dd;

            this.mm=mm;

            this.yy=yy;

            }

            public void disp()

            {

            Console.WriteLine(“My Date of Birth is :”+ dd+”/”+mm+”/”+yy);

            }

            }

(b)       Add the following code into the previous struct definition.

            dob(int dd,int mm, int yy)

            {

            this.dd=dd;

            this.mm=mm;

            this.yy=yy;

            }

Q9.      WAP to calculate the sum of unlimited numbers using params parameter.

Ans.    using System;

            class sumarray

            {

            static void  sum(params int [] arr)

            {

            int s=0;

            foreach(int I in arr)

            {
s=s+I;

            }

            Console.WriteLIne(“sum is “ +s);

            }

            public static void Main()

             {

            Int []x={12,34,45,56};

            sum(x);

            sum(2,3,4,5);

            }

            }

Q10.    Wap to sort the list of items.


Ans.

            using System;

            class numbersorting

            {

            public static void Main()

            {

            int [] number={55,40,80,65,71};

            int n=number.Length;

            Console.Write(“Given list : “);

            for(int i=0;i

            {

            Console.Write(“ “+number[i]);

            }

            Console.WriteLine(“\n”);

 

            for(int i=0;i

            {

            for(int j=i+1;j

            {

            If(number[i]

            {

            Int temp=number[i];

            number[i]=number[j];

            number[j]=temp;

            }

}          
}

Q11.    Wap to set all the diagonal elements of metrics to ‘1’ and other to zero.

Ans.    using System;

            class xyz

            {

public static void main()   {
int [  ]x=new int[3,3];

                        int I,j;

                        for(i=0;i<3 o:p="o:p">

                        {

                        for(j=0;j<3 j="j" o:p="o:p">

                        {

                        Console.Write(“Enter number for metrics”);

                        x[I,j]=int.Parse(Console.readLine());

                        }  }

            for(i=0;i<3 i="i" o:p="o:p">

            {

            for(j=0;j<3 j="j" o:p="o:p">

             {

            If(i==j)

              x[I,j]=1;

            else

            x[I,j]=0;

            }

            }

            //display metrics

            for(i=0;i<3 o:p="o:p">

            {

            for(j=0;j<3 j="j" o:p="o:p">

             {

            Console.Write(“         “+x[I,j]);

            }

            Console.WriteLine();

               }   }

             }

Q12.    Write down the different methods provided by the System. Array class.

Ans.    In c#, every array we create is automatically derived from the System. Array class. This class defines a number of methods and properties that an be used to manipulate array more efficiently

1.    Clear() :- Sets a range of elements to empty values.

2.    CopyTo() :- Copies elements from the source array into the destination array.

3.    GetLength():- Gives the number of elements in a given dimension of the array.

4.    GetValue():- Gets the value for a given index in the array.

5.    Length:-     Gives the length of an array.

6.    SetValue():- Sets the value for a given index in the array.

7.    Reverse():- Reverses the contents of a one-dimensional array.

8.    Sort():- Sorts the elements in a one-dimensional array.

Q13.    List the methods and properties provided by ArrayList class.

Ans.    Add()                           :-          Adds an object to a list

            Clear()                         :-          remove all elements from the ArrayList.

            Contains()                   :-          Determines if an element is in the list

            CopyTo()                     :-          Copies a list to another.

            Insert()                         :-          Inserts an element into the list.

            Remove()                    :-          Remove the first occurrence of an element

            RemoveAt()                :-          Removes the element at the specified place.

            RemoveRange()         :-          Removes a range of elements

            Sort()                           :-          Sorts the elements

            Capacity                      :-          Get or sets the number of elements in the list

            Count                          :-          Gets the number of elements currently in the list.

Q14.    WAP to insert a string between a string.

Ans.    using System;

            class StringMethod     {

public static void main()  {

            string s1=”Lean”;

            string s2=s1.Insert(3,”r”);

            string s3=s2.Insert(5,”er”);

            for(int i=0;i

            Console.Write(s3[i]);

Console.WriteLine();

}   }      

Q15.    Wap to compare two string and find which is greatest.

Ans.    To compare two strings in c# Compare method is used. It return different integer values for different conditions.

1.    Zero Integer if both the string are same

2.    A positive number if first string is greater than  the second

3.    A negative integer if first string is smaller than the second

using System;

class xyz  {

public static void main()  {
string str1=”rajesh”;

string str2=”karan”;

int i;

i=String.Compare(str1,str2);

if(i==0)

Console.WriteLine(“Strings are same”);

else if(i>0)

Console.WriteLine(“first string is bigger than the second”);

else

Console.WriteLine(“first string is smaller than the second”);

}  }

Q16.    List all the methods are properties provided by stringBuilder class.

Ans.    StringBuilder class is used to create Mutable string. It Support many methods and properties that are useful for manipulating dynamic strings.

 

Methods
Operations
Append()
Appends a string
AppendFormat()
Appends strings using a specific format
Insert()
Inserts a string at a specified position
Remove()
Removes the specified character
Replace()
Replaces all instances of a character with a specified one
Properties
Purpose
Capacity
To retrieve or set the number of characters the object can hold
Length
To retrieve or set the Length
MaxCapacity
To retrieve the maximum capacity of the object
[ ]
To get or set a character at a specified position

 

Q17.    Wap to reverse the Array of String.

Ans.    using System;

            class str

            {

            public static void main() 

{

             string[] countries={“India”,”Germany”,”America”,”France”};

int n=countries.Length;

            Array.Sort(countries);

            for(int i=0;i

                        {

                        Console.WriteLine(countries[i]);

}

            Console.WriteLine();

            Array.Reverse(Countries);

            for(int i=0;i

                        {

                        Console.WriteLine(countries[i]);

 } 

 }

                   }   

Q18.    What do you mean by regular expression in c#?

Ans.    Regular expression provide a powerful tool for searching and manipulating a large text. A regular expression may be applied to a text to accomplish following task such as.

1.    To locate substring and return them

2.    To modify one or more substrings and return them

3.    To identify substrings that begin with or end with a pattern of character.

4.    To find all words that begin with a group of characters and end with some other characters.

            The regular expression contain two types of characters.

1.    Literals

2.    Metacharacters

 

Expression
Meaning
“\bm”
Any word beginning with m
“er\b”
Any word ending with er
“B\x\B”
Any x in the middle of a word

 

Q19.    Wap to read strings from a string separated by comma using regular expression.

Ans.    using System;

            using System.Text.RegularExpression;

            class Reg

            {

            string str;

            str=”Amar, Akbar, Antony are friends!”;

            regex r=new regex(“ !, “);

            StringBuilder sb=new StringBuilder();

Int count=1;

foreach(string sub in r.Split(str))

{

sb.AppendFormat(“{0} : {1}\n”,count++,sub);

}

Console.WriteLine(sb);

}

}

Q20.    How can you convert enumerated to base type and base type to enumerated? Show with example.

Ans.    Enum type can be converted to their base type and back again with an explicit conversion using a cast.

           

Following example will show you can convert the enum type to base type. And base type to enum type.

            using System;

            class enumtype

            {

            enum Direction          

            {

            North,

            East=10,

            West,

            South

}

 

public static void main()

{
Direction d1=0;

Direction d2=Direction.East;

Direction d3=Direction.West;

Direction d4=(Direction)12;

Console.WriteLine(“d1 ==”+d1);

Console.WriteLine(“d2 ==”+(int)d2);

Console.WriteLine(“d3 ==”+Direction.West);

Console.WriteLine(“d4==”+d4);

}

}

 

Q21.    What do you mean by nesting of structure? Explain with example.

Ans.    When a structure is define within another structure is called nested structure. C# permits declaration of structs inside other structs.

Following example will show you how a struct can be nested.

using System;

struct employee

            {

public string n;

public int c;

public struct pay

{

public double b;

public double all;

}

}

another way to define nested structure is

struct pay

            {

public double bs;

public double all;

}

struct employee

            {

public string n;

public int c;

public pay s;

}

to access the member of nested structure the following mechanism is used.

employee m;

m.n=”Ravi”;

m.c=120;

m.s.bs=4500;

m.s.all=450;


Section – C                                     2 Marks Questions


          [QUESTIONS 1 TO 32]                              [PAGE 30 TO 34]

 

Q1.      What are structs & how do they differ form classes?


Ans.    C# structure provides a unique way if packing together data of different types. It is a
Differences Between  Class & structure
convenient root for handling a group of logically related data items.


 

 

Category
Classes
Structs
Data type
Reference type & Therefore stored on the heap
Value type & therefore stored on sthe stack behave like simple data type.
Inheritance
Support inheritance
Do not support inheritance
Default values
Default value of a class type is null
Default value is the value produced by ‘zeroing out’ the fields of the struct
Field initialization
Permit initialization of instance fields
Do not permit initialization of instance fields
Constructors
Permit declaration of perameterless constructors
Do not permit declaration of parameterless constructors
Destructors
 Supported
Not supported
Assignment
Assignment copies the reference
Assignment copies the values.

 

Q2.      What are delegates? What is its use in C#?

Ans.    A delegate is c# is a class type object and is used to invoice a method that has been encapsulated into it at the time of its creation. Creating & using delegates involve four steps.

1      Delegate declaration

2      Delegate methods definition

3      Delegate instantiation

4      Delegate invocation

Q3.      Explain the methods of getting input from console are c#.

Ans.    Input from console 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.

e.g.,

using systems;

class samplesix {

public static void Main (string [ ] a ) {

Console. Write (“Welcome to”);

Console. Write (“ “ + a [0]);

Console.WriteLine (“ “ + a [01])

}

}

Q4.      What do you mean by objects?

Ans.    An object is c# is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object.

Objects in c# are created using the new operator. The new operator creates an object of the specified class & returns a reference to that object.

            e.g.      Rectangle rect1.

                        Rect1 = new Rectangle ();

Q5.      Define method overriding.

Ans.    There may be occasions when we want on object to respond to the same method but behave differently when that method is called. The means, we should override the method defined in the super class.

Q6.      Is C# a truly object oriented language? Explain to support your answer.

Ans.    C# is purely object oriented language. It supports all the three tenets of objects-oriented system, namely.

1.    Encapsulation

2.    Inherence

3.    Polymorphism.

The entire C# class model is built on top of the virtual object system (VOS) of. NET framework in C#, every thing is an object. There are no more global functions, variables & constants.

Q7.      What is method overloading?


Ans.    In C# we can create more than one method with the same parameter lists & different definitions. This is called method over loading. Method overloading is used when methods are required to perform similar tasks but using different input parameters.

Q8.      When do we prefer the use of structs over classes?

Ans.    Structs are similar to classes in C#. Although classes will be used to implement most objects, it is desirable to use structs where simple composite data types are required. Because they are value types stored on the stack, they have the following advantages compared to class objects stored on the heap:

·         They are created much more quickly than heap-allocated types.

·         They are instantly & automatically deallocated once they go out of scope.

·         It is easy to copy value type variables on the stack.

            The performance of programs may be enhanced by judicious use of structs

Q9.      What is the purpose of constructor in a structure?

Ans.    Constructors in structure are used to initialize the members of the structures.

Q10.    Why do we declare the data fields as public?

Ans.    We declared data fields as public so that it can be accessed in the different namespaces.

Q11.    What is reusability of code in C#? How is it achieved in C#?

Ans.    Reusability in C# means, that the code once written in C# can be reused again Inter-operability feature. With inter operability C# provides support for using COM objects, no matter what language was used to author them.

Q12.    Define the term reflections.

Ans.    Reflection is used to known about the class, method, properties & events Using reflection we can know the number of methods, events & properties & their syntax.

Q13.    Define polymorphism.

Ans.    When we call a method in an object, C# matches up the method name first and then the number & type of parameters to decide which one of the definitions to execute. This is known as polymorphism.

Q14.    What are Indexers?

Ans.    Indexers are location indicators and are used to access class objects, just like accessing elements in any array. They are useful in cases where a class is container for other objects.

            An Indexer looks like a property and is written the same way a property is written, but with two differences.

1.            The indexer takes an index argument and looks like an array.

2.            The indexer is declared using the name this.

Q15.    What are sealed classes?

Ans.    Sometimes, we may like to prevent a class being further subclassed for security reasons. A class that can not be subclassed is called a sealed class. This is achieved in C# using the modifier sealed as follows:

            Sealed class Aclass

            {

            -------

            ------

            ------

            ------

            }

           

            Sealed class Bclass: someclass

            {

----
----

            }

            Declaring a class sealed prevents any unwanted extensions to the class.

Q16.    What are Sealed methods?

Ans.    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 is to override an inherited virtual method with the same signature. That means, the sealed modifier is always used in combination with the override modifier.

            Syntax

            Access specifier sealed override type functioname()

            {

            }

Q17.    State the characteristics of abstract class.

Ans.   

·         It can’t have implementation.

·         Its implementation must be provided in non-abstract derived classes by overriding the methods.

·         It can be declared only in abstract classes.

·         It can’t take either static or virtual modifiers.

·         An abstract declaration is permitted to override a virtual method.

Q18.    What are abstract method? Also specify the characteristics of these methods.

Ans.    An abstract method is implicitly a virtual method and does not provide any implementation. There fore an abstract method does not have method body.

            Syntax

            public abstract type methodname(parameter);

           


            Following are the characteristics of an abstract method


·         It cannot have implementation

·         Its implementations must be provided in non-abstract derived classes by overriding the method

·         It can be declared only in abstract classes.

·         It  cannot take either static or virtual modifier

·         An abstract declaration is permitted to override a virtual method.

Q19.    What is early binding? How is it achieved.

Ans.    Early binding simply means that object is bound to its method call at compile time. To achieve the early binding we have to define the method of class and then by creating object of that class, method can be attached to the object at compile time.

Q20.    What is late binding ? How it is achieved ?


Ans.    In the polymorphism methods are linked with a particular class much later after compilation, this process is termed as late binding . It is also known as dynamic binding. Virtual methods are used to achieve  the dynamic binding.

 

Q21.    What is multiple inheritance?

Ans.    Multiple inheritance means when a single child inherits more then one parent classes. Using this feature two different classes can communicate with each other . But this feature is not supported by the C#. So communication is C# is achieved by using interfaces.

Q22.    What is encapsulation and Data Hiding?


Ans.    Encapsulation provides the ability to hide the internal details of an object from its users. The outside users may not be able to change the state of an object directly. In C# , encapsulation is implemented

            using the access modifier keywords private, public and protected.

Q23.    Why the operator overloading is used?


Ans.    Operator overloading is the process to use standard operators with user defined data types . It also help us greatly to generate more readable and intuitive code in a number of situations.

1.    Mathematical or physical modeling : where we use classes to represent objects such as coordinates vectors, matrices, tensors, complex numbers 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

Q24.    What are the types of errors?


Ans.    Errors may be broadly classified into  two categories :

1.    Compile time errors.

2.    Run time errors.

Compile time errors are detected and displayed by the C# compiler. A program may compile successfully creating .exe file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. These are known as run time errors.

Q25.    What is exception?


Ans.    An exception is a condition that is caused by a runtime error in the program. When the c# compiler encounters an error such as divided by zero, it creates an exception object and throws it.

Q26.    Define this keyword.

Ans.    this keyword is used for reference to the object that called the method. This reference is available within all the member methods and always refers to the current instance. It is normally used to distinguish between local & instance variables that have the same name.

Q27.    What is an interface?


Ans.    An interface is similar to a class but contains only abstract members. Interfaces are used when we want to implement the concept of multiple inheritances in a program.

Q28.    What do you mean by class?


Ans.    A class is divided by a set of declaration, statements and methods containing instructions known as executable statements. These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules.

Q29.    What do you mean by scope of variables?

Ans.    The scope of a variable is the region of code within which the variable can be accessed. This depends on the type of the variable & place of its declaration. C# defines several categories of variables. They include

·         Static variables

·         Instance variables

·         Array variables

·         Value parameters

·         Reference parameters

·         Local variables

Q30.    Describe the visibility of the class members declared with the following modifiers.

1.    Private                  2. Protected               3. Protected intervals

Ans.    Private: Members are accessible only within the class containing the member.

            Protected:  Member is visible only to its own class & its derived classes.

            Protected internals:  Available in the containing program or assembly and in the 

                                                derived classes.

Q31.    How constant members are declared in c#?

Ans.    The const keyword used as a modifier with variables to declare the member of  the class constant.

            e.g

            public const int size=100;

const members are implicitly static. The value is by definition constant and therefore only one copy of it is stored which is common for all objects of the class. The value of these is fixed.

Q32.    What are static members of a class?

Ans.    The members declared with static keyword are called static members. These members are associated with the class itself rather than with individual objects. So these are often referred to as class variables and class methods. These variable are created when the class is created . these members or variables are shared by all the objects of a class.

 

 

 

 

Section – C                                     5 Marks Questions


          [QUESTIONS 1 TO 25]                               [PAGE 34 TO 48]

 

Q1.      What is a static constructor? How is it different from non-static constructor?

Ans.    A static constructor is called before any object by the class is created. This is useful to do any house keeping work that needs to be done once. It is usually used to assign initial values to static data members. A static constructer is declared by prefixing a static keyword to the constructor definition. It cannot have any parameter e.g.

            class abc 

            {

            Static abc ()

            {

            -------

            -------

            }

            }          

            Static constructor is used only to initialize static members, whereas non-static is used to initialize any member of the class.

Q2.      What are properties in C#? Give example.

Ans.    A properly is a new language feature introduced in C#. They provide the opportunity to protect a field is a class by reading & writing to it through the property. In other languages this is accomplished by programs implementing specialized getter & setter methods. C# properties enables this type of protection while also letting you access the property just like it as a field. A properly is a member that provides access to an attribute of an object or a class. Examples of properties include the length of a string, the size of a font, the (option of a window, the name of a customer, and so on properties can be made read only. This is accomplished by including only a get access or in the property implementation. Write only properly just as you have the read-only proper you can also have write only properly.

            class xyz

            {

            int  x;

            public  property y

            {

            get

            {
return x;

            }

            set

            {

            x=value;

            }

            }

Q3.      What is concatenation? How is it achieved in C#?

Ans.    The binary + operator performs a string concatenation when one or both operands are of type string. If an operand of string catenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual To String () method inherited from the object. If  toString () returns null, an empty string is substituted.

            For e.g.

                        String S1 = “hello”

                        String S2 = “hai”

                        S2+= “World

                        S1 = S2 + “1”

Q4.      WAP to create class & call it from main function.

Ans.    using System;

            class xyz  

            {

            public void disp()

            {

            Console.WriteLine (“Welcome”);

            }

            }

 

            class M

            {

            public static void Main ()

            {

            xyz P = new xyz ( );

            P.disp ();

                              }

            }

Q5.      What is the use “new” operator with method definition?

Ans.    The “new” modifier is used with method definition to specify that the derived class method hides the base class method. Following syntax is used to specify “new” keyword with method definition

            Syntax

            Access specifier new type methodname()

            { 

            }

 

 

Q6.      Write the syntax of exception handling using try catch block n C#.

Ans.    C# uses a keyword try to preface a block of code that is likely to cause an error condition and ‘throw” an

exception. A catch block defined by the keyword catch “catches” the exception “thrown” by the try block    & handles it appropriately. The catch block is added immediately after the try block. The following example illustrates the use of simple try & catch statements.

------

------

try

{

statement;    // generates an exception

}

 

catch (Exception e)

{

statement;   // processes the exception

}

Q7.      What is constructor overloading? Write a c# Program.

Ans.    constructor overloading the process  to define the constructor a same class more than once. To create an overloaded constructor  method, we have to provide several different constructors definitions with different parameter lists. The difference may be in either the number or type of arguments. That is, each parameter list should be unique.

            E.g.

            class room

            {

            public double length;

            public double breadth;

            public room(double x, double y)

            {

            length=x;

            breadth=y;

            }

            public room(double x)

            {

            length=breadth=x;

            }

            public int area()

            {

            return(length* breath);

            }

            }

            class mm

            {

            public static void Main()  {

            room y=new room(24);

            room z=new room(34,45);

            double a,b;

            a=y.area();

            b=z.area();

            Console.WriteLine(“a==” +a);

            Console.WriteLine(“b==” +b);

}  }

Q8.      What is Inheritance? How multiple inheritance is implemented in c#? Give example.


Ans.    Inheritance is the process to create a new class by adding the new feature and extending properties and method of the old class.  C# does not support multiple inheritance with classes. But multiple inheritance is achieved in c# with interfaces.

An interface in c# is reference type . it is basically a kind of class with some differences.

            All the members of an interface are implicitly public and abstract.

            An interface cannot contain constant fields, constructors and destructors

            Its members cannot be declared static

Since the methods in an interface are abstract, they do not include implementation code.

            An interface can inherit multiple interfaces.

           

            Following example will show you how multiple inheritance is achieved

            using System;

            interface addition

            {

            int add();

}
interface multiplication

            {
int Mul();

            }

            class Computation: addition, multiplication

{
int x,y;

            public Computation(int x,int y)

            {

            this.x=x;

            this.y=y;

            }
public int Add()

            {
return (x+y);

            }

            public int Mul()

            {

            return (x*y);

            }

            }

 

            class inter

{
public static void main()

{
Computation com=new Computation(10,20);

            addition add=(addition)com;

            Console.WriteLine(“Sum =” + add.Add());

            Multiplication mull=(Multiplication) com;

            Console.WriteLine(“Product =” + mul.Mul());

            }

            }

 

 

Q9.      What is operator Overloading? How can you overload assignment operator? Write C# program.

Ans.    Operator overloading is one of the many exciting features of object oriented programming. C# supports the idea of operator- overloading to use operators with user defined data types or classes in much the same way as the built in type.

The compounded assignment operators cannot be overloaded in c# like +=, *=, -=, /=, %=

            Only the following operators are overloaded

 

Category

Operators

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

 

Q10.    What is difference between method overloading and overriding methods? Explain with example.

Ans.    Both Method overloading and overriding are used to implement polymorphism in c#. but they have some differences.

           

            Difference between Method overloading and overriding

Method overloading
Method overriding
When more than one method of same name is defined with in the same class with different parameter is called method overloading
When same name method with same return type are defined with in super classes and sub classes it is called method overriding.

           

            Following program will show you to overload method

            class over

            {

            public void line()

{
int I;

            for(I=0;I<79 o:p="o:p">

            {

            Console.Write(“*”);

            }

            public void line(char c)

{
int I;

            for(I=0;I<79 o:p="o:p">

            {

            Console.Write(c);

            }

            }

            Following class will show method overriding

            class xyz

{
public void virtual disp()

            {

            Console.WriteLine(“Display in first class”);

            }

            }

            class pqr: xyz

            {

            public void  override disp()

{
Console.WriteLine(“Display in second class”);

            }

            }

Q11.    (a) Distinguish between string and string builder classes.

Ans.    string class :- string is the predefined reference type we can string to declare string type objects. This class is available in System namespace.

StringBuilder:  Mutable strings that are modifiable can be created using the StringBuilder class. Mutable strings are also  known dynamic strings.

            E.g.

            StringBuilder str1=new StringBuilder (“abc”);

            StringBuilder str2 = new StringBuilder ();

            There are following differences between string and stringBuilder classes

String
StringBuilder
Create store any string type value the string class is used
String builder class create a mutable string that can modify
Following methods are not available in string
Append(), appendFormat(), EnsureCapacity(), Insert()
Remove(), replace()
All these method are available in this class

 

(b)       What is concatenation? How is it achieved in c#?

Ans.    Concatenation is the process to concatenate two string . we can achieve that in c# with “+” operator and  concat() function

            e.g

            string s1=”welcome”;

            string s2=”bye bye”;

            string s3=s1+s2;

Q12.    Write class called date that includes data members day, month and year and methods that could implement the following tasks.

(a)  find a date from keyboard

(b)  display a date

(c)  increment a date by 1 day

(d)  compare two dates to which one is greater

Ans:

            using System;

            class date

            {

            int day,month,year;

            /* to initialize all the member of the date class */

            public date(int day,int month,int year)

            {

            this.day=day;

            this.month=month;

            this.year=year;

            }

            /* Display date in specified format */

            public void disp()

            {

            Console.WriteLine(day+"-"+month+"-"+year);

            }

            /* increment the date by 1 */

            public void incrdate()

            {

            if (day<31 amp="amp" month="month" o:p="o:p">

            day++;

            else if(month<12 o:p="o:p">

            {

            day=1;

            month++;

            }

            else

            {

            day=1;

            month=1;

            year++;

            }

            }

            /* find greater date between two dates */

            public void greater(date d)

            {

            if(year>d.year)

            Console.WriteLine("firstDate is greater than second");

            else if(month>d.month && d.year==year)

            Console.WriteLine("firstDate is greater than second");

            else if(day>d.day && month==d.month && year==d.year)

            Console.WriteLine("firstDate is greater than second");

            else

            Console.WriteLine("Second date is  greater than first");

            }

 

            }

            class xx

            {

            public static void Main()

            {

            date d=new date(12,10,2002);

            date d1=new date(1,10,2003);

            d.disp();

            d.incrdate();

            d.greater(d1);

            d.disp();

            }

            }

Q13.    Differentiate between delegates & interfaces.

Ans.    A delegate is C# is a class type object and is used to invoke a method that has been, encapsulated into it at the time of its creation. Creating & using delegates involves four steps. They include.

·         Delegate declaration

·         Delegate methods definition

·         Delegate instantiation

·         Delegate invocation

A Delegate declaration defines a class using the class system. Delegate as a base class. Delegate

            Methods are any functions (defined in a class) whose signature matches the delegate signature

Exactly. The delegates method. The instance is used to invoke the methods indirectly. An important feature of a delegate is that it can be used to hold reference to a method of any class. The only requirement is that its signature must match the signature of the method. A delegate declaration is a type declaration and takes the following form:

            Syntax      

            Modifier delegate returntype delegate-name (parameters).

Interfaces: - C# provides an approach known as interface to support the concept of multiple inheritance.

An interface in C# is a reference type . It is basically kind of class. An interface can contain one or more methods, properties indexers & events but none of them are implanted in the interface itself. It is the responsibility of the class that implements the interface to define the code for implementation of these members.

The syntax for defining an interface is very similar to that used for defining a class. The general form of an interface definition is:

            interface interfacename

            {

            member declaration;

            }

Q14.    What is the use of  “this” reference in c#? Explain with example.

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

The following example will show you how “this” keyword work

class Integers

{
int x;

int y;

public void setval(int x,int y)

{

this.x=x;

this.y=y;

}

public void disp()

{

Console.WriteLine(“x=”+x);

Console.WriteLine(“y=”+y);

}

}

class my

{
public static void Main()

{

Integer p=new Integer();

p.setval(34,45);

p.disp();

}
}

In this example instance variable and local variable of the method have same name. To distinguish instance variable from local variable this keyword is specified with instance variables in method definition.

 

Q15.    How read only members are declare with in class in c#? Explain with example.

Ans.    There are situations where we would like to decide the value of a constant member at run-time. We may also like to have different constant values for different objects of the class. To overcome these shortcomings, C# provides another modifier known as readonly to be used with data members.

Following example will show the implementation of readonly method.

class Number

{

public readonly int m;

public static readonly int n;

public Number(int x)

{

m=x;

}

static Number()

{

n=100;

}          

}

the value for m is provided at the time of creation of an object using the constructor with parameter x. This value will remain constant for that object.

Q16.    What are properties? How these are different from accessor methods? Write a program to define a property.

Ans.    property is  a mechanism provided by c# .Using a property a programmer can get access to data members as though they are public fields. Same name property  can  be used set or get value from the member of a class.

Syntax

Access specifiers datatype propertyname

{

get

{
return variable;

}

set

{

variable=value;

}

}

 

Accessor methods
Properties
Accessor methods are the simple method used to provide values to member of the class and retrieve value from these members. But different method used to setvalue and different method is used to get value from member of class
Properties are similar to methods but using the same name property we can set or get value from the member of the class

 

The following program is used to set or get value to the member variable of  the class using property

using System;

class Number

{

private in number;

public int setnumber

{

get

{

return number;

}

set

{

number=value;

}
}
}

class property

{

public  static void Main()

{

Number x=new Number();

x.setnumber=34;

Console.WriteLine(“Number =” + x.setnumber);

}
}

Q17.    What do you mean by level of Visibility? How can you specify different level of visibility with class members in c#?

Ans.    Level of visibility is specified with class member to define the life time and scope of  these class members. There different types of access modifier used with class members to specify visibility level.

These modifiers are

1      public

2      private

3      protected

4      internal

public : classes marked public are accessible everywhere, both within and outside the program assembly

private : members declared with private modifiers are only accessible with in the same class in which they are defined.

internal : member declared with internal modifier are accessible in containing classes all the classes with in the same program. But not accessible outside the class.

Protected : members declare with protected keyword are accessible with in the containing class and derived classes of the containing class. But outside of these classes

Protected internal : members declared with protected internal keyword are accessible with in the containing class, their derived classes and all the classes of the containing program.

Following table show the visibility level of class members

Keyword
 
Visibility
 
 
 
Containing classes
Derived classes
Containing program
Anywhere outside the containing program
Private
Yes
No
No
No
Protected
Yes
Yes
No
No
Internal
Yes
No
Yes
 
Protected internal
Yes
Yes
Yes
No
Public
Yes
Yes
Yes
yes

Q18.    What do you by exception list common exception raise by c# program.

Ans.    An Exception is a condition that is caused by a run-time error in the program. When   the c# compiler encounters an error such as dividing an integer by zero. It creates an exception object and throws it.

 

The following exceptions are thrown by certain C# operations.

System.ArithmeticException
A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException.
System.ArrayTypeMismatchException
Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.
System.DivideByZeroException
Thrown when an attempt to divide an integral value by zero occurs.
System.IndexOutOfRangeException
Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.
System.InvalidCastException
Thrown when an explicit conversion from a base type or interface to a derived type fails at run time.
System.NullReferenceException
Thrown when a null reference is used in a way that causes the referenced object to be required.
System.OutOfMemoryException
Thrown when an attempt to allocate memory (via new) fails.
System.OverflowException
Thrown when an arithmetic operation in a checked context overflows.
System.StackOverflowException
Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion.
System.TypeInitializationException
Thrown when a static constructor throws an exception, and no catch clauses exists to catch it.

 

Q19.    What is the use of checked or unchecked operator? Explain with example.

Ans.    checked and unchecked operators are provided by c#. which can be used for checking or unchecking stack overflows during program execution. If an operation is checked , then an exception will be thrown if overflow occurs. If it is not checked, no exception will be raised but we will lose data.

e.g.

using System;

class xyz

{

public static void Main()

{
int a=200000;

int b=300000;

try

{

int m=checked(a*b);

Console.WriteLine(“value of m is : “+m);

}

catch(OverflowExceptin e)

{

Console.WriteLine(e);

}

}
}

In this program a*b produces a value that will easily exceed the maximum value for an “int”, and overflow occurs. As the operation is checked with operator checked, and overflow exception will be thrown

Q20.    How the formatted output is produced in c# program? Explain all the formatted characters.

Ans.    We can produce formatted output using the overloaded WriteLine() method. This method takes a string containing a format and a list of variables whose values have to be printed out. The general form of formatted WriteLine() method is

            Console.WriteLine(format-string,v1,v2,..);

 

            Following character are specified with numeric values

Format
Character
Description
C or c
Currency formatting. By default, the dollar sign $ will be fixed to the value. A precision specifier may be used to specify the number of decimal places
 
D or d
Formats integer numbers., and converts integers to base 10. A precision specifiers may be used to pad with leading zeros
E or e
Exponential formatting. A precision specifi   er may be used to set the number of decimal places, which is 6 by default. There is always one digit before the decimal point.
F or f
Fixed point formatting. The precision specifier decides the number of decimal places zero is acceptable.
G or g
General formatting. Used to format a number to a fixed or exponential format depending on which is the most compact.
N or n
Number formatting: produces values with embedded commas.
X or x
If we use uppercase X, hex format will also contain uppercase characters

 

Q21.    What are Events in c#? Wap that show the simple implementation of event handlers.

Ans.    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 the event.

Events are declared using simple event declaration format

Syntax

Modifier event type event_name;

Eg.

using System;

public delegate void Edelegate(string str);

class eventclass

{

public event Edelegate status;

public void TriggerEvent()

{

if(status !=null)

status(“Event Triggered”);

}

}

class EventTest

            {

public static void Main()

{

EventClass ec=new EventClass();

EventTest et=new EventTest();

Ec.satus+=new Edelegate(et.EventCatch);

Ec.TriggerEvent();

}

public void EventCatch(string str)

{

Console.WriteLine(str);

}

}

Q22.    What is constructor? How the copy constructor is defined in c# class?


Ans.    Constructors are the automatically callable functions. Those are called when the object of the class is created. They are used to initialize the class member with default value. There different types of constructors used with classes in c#.

(a)  Default constructor

(b)  Parameter constructor

(c)  Static constructor

(d)  Copy constructor

 

copy constructor : A copy constructor creates an object by copying variables from another object. It is very useful in the situations where we want to initialize the member of the  object by taking the value of another object of the same class.

Following program will show how copy constructor is used to copy the value of one object into another.

using System;

class item

{
private int code;

private int price;

public item(int code,int price)

{

this.code=code;

this.price=price;

}

public item(item x)

{

code=x.code;

price=x.price;

}

public void disp()

{

Console.WriteLine(“code=”+code);

Console.WriteLine(“price=”+price);

}

}

class m

{

public static void Main()

{

item a=new item(123,450);

itrem b=new item(a);

a.disp();

b.disp();

}
}

Q23.    Wap to define a class between a class.


Ans.

class outer

            {

            class inner

            {

public void disp()

{

Console.WriteLine(“Message from inner class”);

}

}

public void print()

{

inner x=new inner();

x.disp();

Console.WriteLine(“Outer class message”);

}

}

class mm

{

public static void Main()

{
outer a=new outer();

a.print();

}

}

 

Q24.    How an Explicit interface is implemented with a class in c#?

Ans.    c# supports a technique known as explicit interface implementation, which allows a method to specify explicitly the name of the interface it is implementing. Using this technique same name method of different interfaces are implemented to same class.

 

Following program will show how explicit interface is implemented

using System;

interface one

{
void disp();

}
interface two

{

void disp();

}

class third:one,two

{

void one.disp()

{

Console.WriteLine(“One display”);

}

void  two.disp()

{

Console.WriteLine(“two display”);

}

}

class interfacetest

{

public static void Main()

{

third c=new third();

one a=(one) c;

a.disp();

two b=(two)c;

b.disp();

}

}

Q25.    Write a class to represent a vector. Include constructors and methods to

perform the following tasks.

(a) To Create a Vector

(b) To modify the value of a given element.

Ans.    Vector objects can be constructed in a number of ways. The Vector class is an abstract base class and cannot be instantiated directly. Instead, create instances of one of its derived classes.

General vectors


GeneralVector represents a vector with arbitrary components.

Passing a single integer to the constructor creates a GeneralVector with all its components zero. This example creates a vector of length 5:

            GeneralVector v1 = new GeneralVector(5);

(b) 

            // Create a vector, a shallow copy, and a clone:
            Vector v = new GeneralVector(1, 2, 3, 4, 5);
            Vector vShallowCopy = v.ShallowCopy();
            Vector vClone = v.Clone();
            // This prints '2':
            Console.WriteLine("v[1] = {0}", v[1]);
            // Now change the value of the 2nd component.
            v[1] = -1;
            // Component changed. This prints '-1':
            Console.WriteLine("v[1] = {0}", v[1]);
            // Shallow copy changed, also. This prints '-1':
            Console.WriteLine("vShallowCopy[1] = {0}", v[1]);
            // Clone is left unchanged. This prints '2':
            Console.WriteLine("vClone[1] = {0}", v[1]);

 

No comments:

Post a Comment