0% found this document useful (0 votes)
14 views

C# Unit - II

Uploaded by

btechcse21052
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C# Unit - II

Uploaded by

btechcse21052
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

2 Marks
1. What Is C#? (OR) How C# relates to the .NET Framework?(NOV 2013)
C# (pronounced as 'c‘ sharp') is a new computer‐programming language developed by
Microsoft Corporation, USA. C# is a fully object‐oriented language like Java and is the first
Component‐oriented language. It has been designed to support the key features of .NET
Framework, the new development platform of Microsoft for building component‐based
software solutions. It is a simple, efficient, productive and type‐safe language derived from
the popular C and C++ languages. Although it belongs to the family of C / C++, it is a purely
objected‐oriented, modem language suitable for developing Web based applications.
2. What is Characteristic of C#?
 Simple
 Consistent
 Modern
 Object - Oriented
 Type - Safe
 Versionable
 Compatible
 Interoperable
 Flexible
3. What are the APPLICATIONS OF C#?
 . Console applications
 . Windows applications
 . Developing Windows controls
 . Developing ASP.NET projects
 . Creating Web controls
 . Providing Web services
 . Developing .NET component library
4. List out the features of C++, which are dropped in C#?
The following features of C++ are missing in C#:
 Macros
 Multiple Inheritance
 Templates
 Pointers
 Global Variables
 typedef statement

U20CSCMO2 - C# AND NETPROGRAMMING 1


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 Default arguments
 Constant member functions or parameters
 Forward declaration of classes.
5. What are the enhancements done to C++ in C# environment?
C# modernizes C++ by adding the following new features:
 Automatic Garbage Collection
 Versioning support
 Strict type‐safety.
 Properties to access data members
 Delegates and events
 Boxing and unboxing
 Web Services.
6. List out the two types C# programs?
C# can be used to develop two categories of programs, they are,
a) Executable application programs (.exe) b) Component Libraries (.dll)
7. What are the major highlights of C#?
• It simplifies and modernizes C++
• It is the only component‐oriented language available today.
• It is the only language designed for the .NET Framework
• It combines the best features of many commonly used languages: the productivity of visual
basic, the power of C++ and the elegance of Java
• It is intrinsically object‐oriented and web‐enabled.
• It has a lean and consistent syntax.
8. List out some problems of C and C++
• They have long cycle‐time.
• They are not truly object‐oriented.
• They are not suitable for working with new web technologies.
• The have poor type‐safety.
• They are prone to costly programming errors.
• They do not support versioning.
• They are prone to memory leakages.
• They are weak in consistency
9. What is the limitation of Visual Basic?
Since Visual Basic is not truly an object‐oriented programming language, it becomes
increasingly difficult to use when systems become large.
U20CSCMO2 - C# AND NETPROGRAMMING 2
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

10. What are the limitations of using Java language?


• Java has not retained some powerful C++ features such as operator overloading.
• It also lacks inter‐operability with code developed in other languages.
11. What are important features of C#, which are adopted from other languages? (Apr’15)
C# borrows Java‘s features such as grouping of classes, interfaces and implementation
together in one file so that programmers can edit the code more easily. C# also handles objects
using references, the same way as Java. C# borrows VB‘s approach to form design, namely,
dragging controls from a tool box, dropping them onto forms, and writing event handlers for
them.
12. What is Command Line Argument?
There may be occasions when we may like our program to behave in a particular way
depending on it input provided at the time of execution. This is achieved in C# by using
what are known as command line arguments. Command line arguments are parameters
supplied to the Main method at the time of invoking it for execution.
13. What is comment? List out its types?
The statements which are not included for compilation by the compiler are called as
comments. They are used to enhance readability and understanding of code. C# permits two
types of comments, namely:
Single Line Comments
Begins with a double backslash (//) symbol. Ex: //Main method begins Multi Line Comments
This starts with /* characters and terminates with */. Ex: /* Program - Testing Delegates
Date - 09.10.08
Developer - Kumaran */
14. State the C# Program Structure.
C# program contains following sections in it:
a) Documentation Section
b) Using Directive Section
c) Interfaces Section
d) Classes Section
e) Main Method Section
15. C# is a freeform language. Comment
C# is a freeform language. So it does not care where on the line the code is begins.
Ex:
System.Console.WriteLine(“Hello ECE”); Can be written as
System.Console.WriteLine (“Hello ECE”);

U20CSCMO2 - C# AND NETPROGRAMMING 3


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Can be written as
System.Console.WriteLine
(
“Hello ECE”
)
;
16. What are the types of tokens available in C#?
C# has five types of tokens. They are,
a) Keywords
b) Identifiers
c) Literals
d) Operators
e) Punctuators
17. What are keywords?
Keywords are an essential part of a language definition. They implement specific features of
the language. They are reserved, and cannot be used as identifiers except when they are prefaced
by the @ character. There are 79 keywords in C#. Ex: public, private, if, while etc..
18. What are identifiers?
Identifiers are programmer‐designed tokens. They are used for naming classes, methods,
variables, labels, namespaces, interfaces, etc. C# identifiers enforce the following rules:
They can have alphabets, digits and underscore characters. They must not begin with a digit
Upper case and lower case letters are distinct
Keywords in stand‐alone mode cannot be used as identifiers
C# permits the use of keywords as identifiers when they are prefixed with a ‗@‘ character.
19. What are the lexical elements of C#?
1. Comments
2. white spaces
3. tokens
4. preprocessing directives
20. What is line terminator in C#?
A new line character is known as line terminator in C#. The following characters
are treated as line terminators:
• The carriage return character (U+000D)
• The line feed character (U+000A)
• The carriage return character followed by a line feed character.

U20CSCMO2 - C# AND NETPROGRAMMING 4


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

• The line separator character (U+2028)


• The paragraph separator character (U+2029)
21. What are punctuators?
Punctuators are symbols used for grouping and separating code. They define the shape
and function of a program. Punctuators or Separators in C# include:
 Parentheses ()
 Braces { }
 Brackets []
 Semicolon ;
 Colon :
 Comma ,
 Period .
22. What is stack memory and heap memory?
Stack - Represents a portion of memory that can be used by the program at runtime. This
memory is not subject to garbage collection. The lifetime of the variables stored in stack is
limited to the lifetime of the block in which it is defined. Method states are allocated on
stack. Thus, local variables, arguments of methods, and local object references are allocated
on stack memory.
Heap - This is the region of memory used for dynamic storage. It is reserved for a program to
use for the temporary storage of data structures whose existence or size cannot be determined
until the program is running. It is subjected to garbage collection. The problem of memory
leak is avoided in this type of memory allocation.

U20CSCMO2 - C# AND NETPROGRAMMING 5


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

23. What are statements?


Statements in C# are like sentences in natural languages. A statement is an executable
combination of tokens ending with a semicolon. C# implements several types of statements.
They include:
Empty Statements
Labeled statements
Declaration statements
Expression statements
Selection statements
Interaction statements
Jump statements
The try statements
The checked statements
The unchecked statements
The lock statements
The using statements
24. What are escape sequences?
C# supports special backslash character constants that are used in output methods.
These character combinations are called as escape sequences. Some escape sequences are:
\n new line
\t horizontal tab
\f form feed
\r carriage return
\b backspace
25. What is NaN?
Floating‐point data types support a special value known as Not‐a‐Number (NaN).
NaN is used to represent the result of operations such as dividing zero by zero, where an actual
number is number is not produced. Most operations that have NaN as an operand will produce
NaN as a result.

U20CSCMO2 - C# AND NETPROGRAMMING 6


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

26. Which types of variables are initialized with default value?


The following categories of variables are automatically initialized to their default values.
Static variables
Instance variables
Array elements
27. What is the default value for built‐in data types?
All integer type 0
char type ‗\x000‘
float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference types null
28. How constants are created in C#?
The constants can be created by using any one of the method:
usingconst keyword
Ex:constint ROW = 10;
const float PI = 3.14;
using #define statement (symbolic constants)
Ex:#define ROW 10
#define PI 3.14
29. What are the advantages of using constants?
Constants make programs easier to read and understand Easy to modify the program. They
minimize accidental errors, like attempting to assign values to some variables which are
expected to be constants.
30. Classify the C# operators.
C# operators can be classified into a number of related categories as below:

U20CSCMO2 - C# AND NETPROGRAMMING 7


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and decrement operators
 f)Conditional operators
 Bitwise operators
 Special operators
31. What are special operators available in C#?
C# supports the following special operators:
is (relational operator)
as (relational operator)
typeof (type operator)
sizeof (size operator)
new (object operator)
.(dot) (member‐access operator)
checked (overflow checking)
unchecked (prevention of overflow checking)
32. What is the advantage of using foreach loop?
The advantage of foreach over for statement is that it automatically detects the
boundaries of the collection being iterated over. Further, the syntax includes a built‐in
iterator for accessing the current element in the collection.

U20CSCMO2 - C# AND NETPROGRAMMING 8


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

33. How the compiler selects a method for compilation?


The method selection involves following steps:
1. The compiler tries to find an exact match in which the types of actual parameters
are the same and uses that method.
2. If the exact match is not found, then the compiler tries to use the implicit conversions to the
actual arguments and then uses the method whose match is unique. If the conversion
creates multiple matches, then the compiler will generate an error message.
42. Can a method return more than one value in C#? Justify your answer.

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

U20CSCMO2 - C# AND NETPROGRAMMING 9


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
43. What is a class? (May-22)
A class is essentially a description of how to construct an object that contains fields
and methods. It provides a sort of template for an object and behaves like a basic data type
such as int. Classes provide a convenient approach for packing together a group of logically
related data items and functions that work on them.
49. List out the member access modifiers in C# (APR 2012)
private - Member is accessible only within the class containing the member.
public - Member is accessible from anywhere outside the class as well. It is also
accessible in derived classes.
protected - Member is visible only to its own class and its derived class.
internal - Member is available within the assembly or component that is being created but not to
the clients of the component.
protected internal - Available in the containing program or assembly and in the derived classes.
50. What are properties?
Properties have the same capabilities as accessor methods, but are much more elegant and
simple to use. Using a property a programmer can get access to data members easily. These are
sometimes referred as ―smart fields‖.
Ex:
classTestProp
{
privateint n;
publicint number //property defines getter and setter methods
{
get
{
return n;
}
set
{
number = value;
}
}
}

U20CSCMO2 - C# AND NETPROGRAMMING 10


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

51. What are the powerful features of properties?


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

52. What are indexers?


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

53. Differentiate indexer from property.


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

U20CSCMO2 - C# AND NETPROGRAMMING 11


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

A set accessor of a property corresponds to a method with a single parameter named


value, whereas a set accessor of an indexer corresponds to a method with the same formal
parameter list as the indexer, plus the parameter named value. It is an error for an indexer to
declare a local variable with the same name as an indexer parameter. The indexer takes an index
argument and looks like array. The indexer is declared using the name this.

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

63. What is Regular expression?(APR-12)


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

82. Differentiate Property and Indexer


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

U20CSCMO2 - C# AND NETPROGRAMMING 12


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

72. Define Delegate? (APR 2012)


It is an Event handling mechanism of .NET. To raise events, a class must define one
delegate per event type. To handle events, types must implement one event handler per
event type. Delegates can reference both instance and static methods. C# uses the delegate
keyword.
73. What are steps involved in using delegates in a C# program?
1. Delegate declaration
2. Delegate methods definition
3. Delegate instantiation
4. Delegate invocation

74. Write a note on delegates.


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

75. What is an event? (Apr’16)


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

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


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

U20CSCMO2 - C# AND NETPROGRAMMING 13


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
83. Use a diagram and briefly discuss the evolution of C# Language (Nov’15)

C# Versions
 C# 1.0 – It was the first release and was included in Visual Studio.Net.

 C# 1.1 – It was released after the first release and Microsoft changed the Visual Studio
toVisual Studio.Net 2003 in year 2003.
 C# 2.0 – It was released in year 2005 as Visual Studio 2005.
 C# 3.0 – It was released with the same Visual Studio with the previous one and it was
integrated with Windows Vista and Server 2008.
 C# 3.5 – AJAX – Visual Studio 2008
 C# 4.0 – It was released with the Visual Studio 2010.
 C# 4.5 – It was released with the Visual Studio 2012.
 C# 4.5.1, 4.5.2 – It is released with Visual Studio 2013.

84. How to declare a one-dimensional array in C# (Nov’14)


Creation of an array involves three steps.
1. Declaring the array (Declaration of Arrays).
2. Creating memory locations (Creation of Arrays).
3. Initialization of Arrays.
1 . ) Declaration of Arrays:-
Arrays are declared in C# as follows:-
Syntax:
type [ ] arrayname ;
Ex.
int [ ] num;


U20CSCMO2 - C# AND NETPROGRAMMING 14


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

5 Marks
1. Explain what is an object and class
OBJECTS:(NOV 12)(Apr’16) (2 Mark)
Anything that we can describe, can be represented as an object, and that representation
can be created, manipulated and destroyed to represent how we use the real objects that it
models.
Example: Car, book, building etc;
DEFINING A OBJECT:
An object is a self-contained entity with attributes and behaviors.
Attributes: Information an object must know:
 Identity – uniqueness
 Attributes – Structure
 State – Current Condition

Behavior: Behavior an object must do:


 Methods – what it can do
 Events – what it responds to
In object-oriented programming, objects communicate and interact with each other using
messages.

CLASS:
A class describes in abstract all of the characteristics and behavior of a type of object.
Once instantiated, an object is generated that has all the methods, properties and other behavior
defined within the class.

PERSON
Name
Sex
Age
Tellsex ()
Tellage ()

SYNTAX FOR CREATING CLASS:


The basic syntax for the creation of a new class is very simple. The keyword ‗class‘

U20CSCMO2 - C# AND NETPROGRAMMING 15


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

followed by the name of the new class is simply added to the program. This is then followed by a
code block surrounded by brace characters { } to which the class code will be added.
Class class_name { }
Namespace classTest
{
Class vehicle
{
}
}

INSTANTIATING THE CLASS


Although we have not explicitly added any functionality to the class, it can now be instantiated
to create objects. These objects will have the standard behavior of all classes.
Static void Main (string [] args)
{
Vehicle car = new vehicle ();
}

3. Explain Indexer In C# (May’14)

 C# introduces a new concept called Indexer. This is very useful for some situation. Let us
discuss something about Indexer.

 Indexer concept is object act as an array.


 Indexer, an object to be indexed in the same way as an array.
 Indexer modifier can be private, public, protected or internal.
 The return type can be any valid C# types.
 Indexers in C# must have at least one parameter. Else the compiler will generate a
compilation error.
This [parameter]
{
Get
{
// get codes here
}
Set

U20CSCMO2 - C# AND NETPROGRAMMING 16


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
// set codes goes here
}}

The general syntax is given below,


[modifiers] <type> this [<parameters>]
{
[get { <stmts>;}] // get Accessor
[set { <stmts>;}] // set Accessor
}
Where,
Modifiers – can be private, public, protected or internal.
Return type – can be any valid C# types.
this – is a special keyword in C# to indicate the object of the current class.
<parameters> - The formal argument – list specifies the parameters of the indexers.
Example for C# Indexer:
Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Indexers
{
Class ParentClass
{
Private string [ ] range = new string [5];
Public string this [ intindexrange]
{
Get
{
Return range [ indexrange];
}
Set
{
Range [indexrange] = value;
}}}
Class ChildClass

U20CSCMO2 - C# AND NETPROGRAMMING 17


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
Public static void Main ()
{
ParentClassobj = new ParentClass ();
obj [0] =‖ONE‖;
obj [1] =‖TWO‖;
obj [2] =‖THREE‖;
obj [3] =‖FOUR‖;
obj [4] =‖FIVE‖;
Console.WriteLine (―Welcome to C# Home Page/n‖);
Console.WriteLine (“\n”);
Console.WriteLine (“{0}\n, {1}\n, {2}\n, {3}\n, {4}\n”, obj [0], obj
[1], obj [2], obj [3], obj [4]);
Console.WriteLine ();
Console.ReadLine ();
}}}

4. Explain Regular Expressions In Detail.


The System.Text namespaces provides a number of classes for regular expression
processing. Regular Expressions offer a powerful, flexible and efficient strategy for processing
text.
Common Regular Expressions Meta characters:

EXPRESSION MEANINGS
Matches any characters except \n
[characters] Matches a single character in the list.
[^characters] Matches a single character not in the list.
[char X – char Y] Matches a single character in the specified range.
\w Matches a word character
\W Matches a non-word character
\s Matches a white space character
\S Matches a non-white character.

U20CSCMO2 - C# AND NETPROGRAMMING 18


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Class splitRegExApp
{
Static void Main (string [ ] args)
{
String S = “Once upon A Time in America”;
Char [ ] seps = new char [ ] {‗ ‗};
Regex r = new Regex (― ―);
Foreach (string ss in S.Split (S))
{
Console.WriteLine (ss);
}}}
OUTPUT:
Once
Upon
A Time
In
America
Match and Match Collection:
The System.Text namespace also offers a Match class represents the results of a regular
expression – matching operation. A match object is immutable, and the Match class has no
public constructor. In the following example, we use the Match method of the Regex class to
return an object of type Match in order to find the first Match in the input string.
Class MatchingApp
{
Static void Main (string [ ] args){
Regex r = new Regex (“in”);
Match m = r.Match (“Matching”);
If (m.success){
Console.WriteLine(“Found ‘{0}’ at position {1}”,m,value,m,Index);
}}}

U20CSCMO2 - C# AND NETPROGRAMMING 19


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

OUTPUT

Found ‘in‘ at position 5.


Groups and Captures:
The System.Text namespace also offers a group class and a group collection class. The group
class represents the results from a single regular expression – matching group.
In the following example, we define three groups, “ing”, “in”, and “n” and then search the string
“Matching” to find these patterns.
Class GroupingApp
{
Static void Main (string [ ] args)
{
Regex r = new Regex (“i(n))g”);
Match m = r.Match (“Matching”);
GroupCollectiongc = m.Groups;
Console.WriteLine (“Found {0} Groups”, gc.Count);
For (int i=0; i<gc.Count; i++)
{
Group g = gc[i];
Console.WriteLine (“Found ‘{0}‘ at position {1}”, g.Value, g.Index);
}}}
OUTPUT:
Found 3 Groups
Found ‘ing’ at position 5
Found ‘in‘ at position 5
Found ‘n‘ at position 6

U20CSCMO2 - C# AND NETPROGRAMMING 20


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

5. Discuss different ways in which C# is different from Java


(Nov’15)Features of C# Absent in Java
 C# includes more primitive types and the functionality to catch arithmetic exceptions.
 Includes a large number of notational conveniences over Java, many of which, such as
operator overloading and user-defined casts, are already familiar to the large community
of C++ programmers.
 Event handling is a "first class citizen"—it is part of the language itself.
 Allows the definition of "structs", which are similar to classes but may be allocated on
the stack (unlike instances of classes in C# and Java).
 C# implements properties as part of the language syntax.
 C# allows switch statements to operate on strings.
 C# allows anonymous methods providing closure functionality.
 C# allows iterator that employs co-routines via a functional-style yield keyword.
 C# has support for output parameters, aiding in the return of multiple values, a feature
shared by C++ and SQL.
 C# has the ability to alias namespaces.
 C# has "Explicit Member Implementation" which allows a class to specifically
implement methods of an interface, separate from its own class methods. This allows it
also to implement two different interfaces which happen to have a method of the same
name. The methods of an interface do not need to be public; they can be made to be
accessible only via that interface.
 C# provides integration with COM.
 Following the example of C and C++, C# allows call by reference for primitive and
reference types.
Features of Java Absent in C#
 Java's strictfp keyword guarantees that the result of floating point operations remain the
same across platforms.
 Java supports checked exceptions for better enforcement of error trapping and handling.
Philosophical Differences between the Languages
 There are no unsigned primitive numeric types in Java. While it is universally agreed that
mixing signed and unsigned variables in code is bad, Java's lack of support for unsigned
numeric types makes it somewhat unsuited for low-level programming.
 C# does not include checked exceptions. Some would argue that checked exceptions are
very helpful for good programming practice. Others, including Anders Hejlsberg, chief

U20CSCMO2 - C# AND NETPROGRAMMING 21


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

C# language architect, argue that they were to some extent an experiment in Java and that
they haven't been shown to be worthwhile [1] [2].
 C#'s namespaces are more similar to those in C++. Unlike Java, the namespace does not
specify the location of the source file. (Actually, it's not strictly necessary for a Java
source file location to mirror its package directory structure.)
 C# includes delegates, whereas Java does not. Some argue that delegates complicate the
method invocation model, because they are handled through reflection, which is
generally slow. On the other hand, they can simplify the code by removing the need to
declare new (possibly anonymous) classes to hook to events.
 Java requires that a source file name must match the only public class inside it, while C#
allows multiple public classes in the same file.
 C# allows the use of pointers, which some language designers consider to be unsafe, but
certain language features try to ensure this functionality is not misused accidentally.
Pointers also greatly complicate technologies such as Java's RMI (Remote Method
Invocation), where program objects resident on one computer can be referenced within a
program running on an entirely separate computer. Some have speculated that the lack of
memory pointers in Java (substituted by the more abstract notion of object references)
was a nod towards the coming of grid computing, where a single application may be
distributed across many physical pieces of hardware.
 C# supports the goto keyword. This can occasionally be useful, but the use of a more
structured method of control flow is usually recommended.
 C# has true multi-dimensional arrays, as well as the array-of-arrays that is available to
Java (which C# calls jagged arrays). Multi-dimensional arrays are always rectangular (in
the 2D case, or analogous for more dimensions), whereas an array-of-arrays may store
rows (again in the 2D case) of various lengths. Rectangular arrays may speed access if
memory is a bottleneck (there is only one memory reference instead of two; this benefit is
very dependent on cache behavior) while jagged arrays save memory if it's not full but
cost (at the penalty of one pointer per row) if it is. Rectangular arrays also obviate the
need to allocate memory for each row explicitly.
 Java does not include operator overloading, because abuse of operator overloading can
lead to code that is harder to understand and debug. C# allows operator overloading,
which, when used carefully, can make code terser and more readable. Java's lack of
overloading makes it somewhat unsuited for certain mathematical programs. Conversely,
.NET's numeric types do not share a common interface or superclass with
add/subtract/etc. methods, restricting the flexibility of numerical libraries.

U20CSCMO2 - C# AND NETPROGRAMMING 22


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 Methods in C# are non-virtual by default. In Java however, methods are virtual by


default. Virtual methods guarantee that the most overridden method of an object will be
called which is determined by the runtime. You always have to keep that in mind when
calling or writing any virtual method! If the method is declared as non-virtual, the
method to invoke will be determined by the compiler. This is a major difference of
philosophy between the designers of the Java and .NET platforms.
 Java 1.5's generics use type-erasure. Information about the generic types is lost when
Java source is compiled to bytecode. .NET 2.0's generics are preserved after compilation
due to generics support starting in version 2.0 of the .NET Common Language Runtime,
or CLR for short. Java's approach allows Java 1.5 binaries to be run in the 1.4 JRE, at the
cost of additional runtime typechecks.
 C# is defined by ECMA and ISO standards, whereas Java is proprietary, though largely
controlled through an open community process.
 The C# API is completely controlled by Microsoft, whereas the Java API is managed
through an open community process.
 The .NET run-time allows both managed and unmanaged code, enabling certain classes
of bugs that do not exist in Java's pure managed code environment but also allows
interfacing with existing code.

10 Marks

1. What is meant by c# language fundamentals? (Apr’15) (May-22)


To analyze the C# language fundamentals we must analyze the following.
 C# Source File Structure.
 C# Keywords
 Identifiers.
 Variable and Data types.
 Variable Declaration and Initialization
 Operators
 Flow Controls.
I. C# SOURCE FILE STRUCTURE
DECLARATION ORDER
1. Using Statement
It is used to reference the namespaces.
Example: Using System.
2. Namespace Declaration
U20CSCMO2 - C# AND NETPROGRAMMING 23
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
It is used to logically group similar classes that have related functionality. In C#
we need to declare each class in a namespace. By default namespace is
automatically created with the same name as that of the project.

Example: namespace CsharpSchool


3. Class Declaration
A C# source file can have several classes but only one class have the Main
method.

Example: public class CSharpOne


COMMENTS:
1. Single-line Comment:

Example: //print a message.

2. Multi-line Comment:
Example: /*
Created on Feb 22, 2005
First C# program

*/
3. Documentation Comment:
Example: ///<summary>
///</summary>
///<param> name=‖args‖ </param>
WHITESPACES
Tabs and spaces are ignored by the compiler. They are used to improve the readability of the
code.
CLASS
Every C# program includes at least one class definition. The class is the fundamental component
of all C# programs. Class is keyword.
Example: public class CSharpOne
{
……
……

U20CSCMO2 - C# AND NETPROGRAMMING 24


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
……
}
A class definition contains all the variables and methods that make the program work. This is
contained in the class body indicated by the opening and closing braces.
BRACES
Braces are used for grouping statements or block of codes.
The left brace ({) indicates the beginning of a class body, which contains any variables and
methods the class needs.
The left brace also indicates the beginning of a method body.
For every left brace that opens a class or method we need a corresponding right brace (}) to close
the class or method.
A right brace always closes its nearest left brace.
MAIN () METHOD:
This line begins the Main() method. This is the line at which the program will begin executing.
Example: public static void Main(String[] args)
{
……
……
}
STRING ARGS []
Declares a parameter named args, which is an array of string. It represents command-line
arguments.
(string[] args)
C# Statement
A complete unit of work in a C# program. A statement is always terminated with a semicolon
and may span multiple lines in our source code.
Example: (―Welcome to C#‖)
CONSOLE.WRITELINE ()
This line outputs the string, followed by a newline on the screen.
Example: Console.WriteLine (―Welcome to C#)
TERMINATING CHARACTER:
Semicolon (;) is the terminating character for any C# Statement.
II. C# KEYWORDS:
Keywords are an essential part of language definition as they implement specific features of
the language. They are reserved, and cannot be used as identifiers.

U20CSCMO2 - C# AND NETPROGRAMMING 25


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
abstract as Base bool break byte case
catch char checked class const continue decimal
default delegate Do double else enum event
explicit extern False finally fixed float for
foreach goto If implicit in int interface
internal is Lock long namespace new null
object operator Out override params private protected
public readonly Ref return sbyte sealed Short
sizeof stackalloc Static struct switch this Throw
true try typeof uint ulong unchecked Unsafe
ushort using virtual volatile void while

III. IDENTIFIER:
An identifier is the name given by a programmer to a variable, statement label, method,
class, and interface.
- An identifier must begin with a letter.
- Subsequent characters must be letters, digits or underscore.
- An identifier must not be a C# keyword.
- Identifier must not be a C# keyword.
- Identifiers are case sensitive.
- Keywords can be used as identifiers, when they are prefixed with the ‗@‘ character.
INCORRECT CORRECT
3 strikes Strikes3
Write&Print Write_Print
switch Switch
- printMe is not same as PrintMe.
IV. VARIABLE AND DATATYPES:
A Variable is a named storage location used to represent data that can be changed while
the program is running.
CONSTANT VARIABLES:
Variables whose do not change during execution of a program.
- Use the const keyword to initialize.
- Constants can be initialized using an operator.
- Constants cannot use non_const values in an expression.
CORRECT FORM INCORRECT FORM

U20CSCMO2 - C# AND NETPROGRAMMING 26


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Constint age = 21; Constint;
age = 21;
Constint m = 10; int m= 10;
Constint age = m*5; constint age = m*5;

DATATYPES:
A datatype determines the values that a variable can contain and the operations
that can be performed on it.
Categories of datatypes include:
- Value Types.
- Reference Types.
- Pointers.
VALUE DATA TYPES:
Pre defined value types are also known as simple types or primitive types.
REFERENCE DATA TYPES:
Reference Data Types represent objects. A reference serves as a handle to do the object;
it is a way to get to the object. C# reference data types are derived into two types.
- User Defined (or complex) types.
 Class
 Interfaces
 Delegates
 Arrays
- Pre-defined (or simple) types.
 Object type
 String type
V. VARIABLE DECLARATION AND INTIALIZATION:
To declare a variable with value data type.
Int age = 21;
To declare a variable with reference data type.
String name = ―Jason‖;
VALUE TYPE DECLARATION
DECLARATION:
Int age;
INTIALIZATION/ASSIGNMENT:
age = 17;

U20CSCMO2 - C# AND NETPROGRAMMING 27


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
REFERENCE TYPE DECLARATION
Car mycar;
mycar = new Car (“Bumble Bee”);
VI. OPERATORS:
Unary Operators (++, --, +, -, ~, ( ) )
Arithmetic Operators ( *, ?, %, +, -)
Shift Operators (<<, >>, >>>)
Comparison Operators (<, <=, >, >=, ==, !=)
Bitwise Operators (&, ^, |)
Logical Operators (&&, ||, !)
Conditional Operators (?, :)
Assignment Operators (=, +=, -=, *=, /=)
VII. FLOW CONTROLS:
 if_else () Statement
 switch () statement
 while () statement
 do_while () statement
 for statement
 foreach statement
 break statement

 goto statement
 continue statement
 label statement
1. If_else statement:
if (condition) {
//statements
}
else {
//statements
}
Switch statement:
C# does not allow automatic ―fall-through‖. ―Fall-through‖ is allowed only if the
case block is empty.
For two consecutive case blocks to be executed continuously, we have to force the

U20CSCMO2 - C# AND NETPROGRAMMING 28


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
process by using the goto statement.
Switch (m) { switch (m) { switch (m) {
Case 1: Case 1: Case 1:
x= y; x=y;
Case 2: Case 2: goto case 2;
x= y - m; x= y + m; Case 2:
Default: Default: x= y + m;
x= y - m; x= y - m; Default:
} } x= y - m;
}
2. While statement:
while (condition) {
//statements
}
3. for statement:
for (init; condition; exp) {
//statements
}
4. for each statement:
foreach (type variable in exp)}
//statements

}
5. Break statement:
break;
6. Continue statement:
continue;
7. Label and goto statement:
Label and goto are used in combination. Labels can be used anywhere in the
program and goto is used inside loops to start a new iteration.
Gotolabelname;
Label name;
Example:
for (int i=0; i<10; i++)
{
while (x<5)
U20CSCMO2 - C# AND NETPROGRAMMING 29
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
{
Y=i*x;
console.writeline (y);
If (y>10)
goto Out1;
x=x+1;
}
}
Out 1:
console.writeline (―out of loop‖);
8. Return statement:
The return branching statements is used to exit from the current method.
There are two forms:
- Return <value>;
- Return;
Example 1:
Public int sum (int x, int y) {
Return x+y;
}
Example 2:

Public int sum (int x, int y) {


x=x+y;
if (x<100) {
return x;
} else {
return x+5;
}
}
Example 3:
Public void get sum (int x) {
System.console.writeline (x);
Return;
}

U20CSCMO2 - C# AND NETPROGRAMMING 30


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

6. Explain Methods Fields And Properties. (Apr 2013)


METHODS:(NOV 2012) (2 Mark)
There are 2 types of methods that can be created for a class.

- Public Methods
- Private Methods

PUBLIC METHODS:
Public methods are part of the class public interface. I.e. these are the methods that can be
called by other objects. To create a public method a ―public‖ keyword must be used as prefix.
Public void PressHorn ()
{
Console.writeline (―TOOT TOOT!‖);
}
Static void Main (string [] args)
{
Vehicle car = new vehicle ();
car.PressHorn ();
}

PRIVATE METHODS:
To provide for encapsulation, where the internal functionality of the class is hidden, some
methods will be defined as private. Methods with a private protection level are completely
invisible to external classes. This makes it safe for the code to be modified to change
functionality, improve performance, etc, To define a method, as private, the private keyword can
be used as a prefix to the method.
Private void MonitorOilTemperature ()
{
//Internal oil Temperature Monitoring Code…;
}
To demonstrate that this method is unavailable to external classes, try the following code
in the main method of the program. When we attempt to compile or execute the program, an
error occurs indicating that the MonitorOilTemperature method cannot be called due to its
protection level.
Static void Main (string [] args)

U20CSCMO2 - C# AND NETPROGRAMMING 31


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
{
Vehicle car = new vehicle ();
car.MonitorOilTemperature ();
}

FIELDS:
Fields in a class are used to hold data. Fields can be marked as public, private, protected,
internal, or protected internal. A field can optionally be declared static. A field can be declared
readonly. A readonly field can only be assigned a value during initialization or in a constructor.
A field can be given an initial value by using the assignment operator when the field is declared.
Fields should generally be private with access to fields given by using properties.
Public class car
{
Public string make =”ford”
}
Fields are initialized immediately before the constructor for the object instance is called, so if the
constructor assigns the value of a field, it will overwrite any value given during field declaration.
Public class car
{
Public string make =
“ford”; Public car ()
{
Make = “Alfa”;
}
}
PROPERTIES:
Adding a property to a class is similar to adding a variable.

Public int width


{
}
Once declared, functionality must be added to the property. This is achieved with the use of get
and set accessors.
Get accessor - code block that control how the property‘s value is retrieved or calculated when
requested.
Set accessor – how the properties value is validated, processed and stored when assigned a value.
U20CSCMO2 - C# AND NETPROGRAMMING 32
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
The two accessors are added to the property using the get and set keywords, each with its own
code blocks.
Public int width
{

Get
{
……….
……….
}
Set
{
……….
……….
}
}
To complete the width method, we now need to add the code that processes the getting
and setting of the properties. This is relatively simple for the get accessor. When the property
value is requested, we will simply return the value from the class-level variable.
Public int width
{
Get
{
Return width;
}
Set
{
}
}
When using the set accessor, the value that the external objects is assigning to the
property is passed as a variable named ―value‖. This can be thought of as similar to a method
parameter even though its name is hidden. For the width property, we will validate the provided
value before storing it. If the value is negative or is greater than one hundred, an exception will
be thrown and the property will remain unchanged. This is possible because of the correct usage
of the get and set accessors.
Example:
U20CSCMO2 - C# AND NETPROGRAMMING 33
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Public int width
{
Get
{

Return width;
}
Set
{
If(value<0||value >100)
{
Throw new overflowException ();
}
Width value;
}}
Public int height
{
Get
{
Return height
}
USING PROPERTIES:
Properties of instantiated objects are accessed using the object name followed by the member
access operator (.) and the property name. The property can be read from and written to using
similar syntax as for a standard variable.
Example:
Static void main (String [] args)
{
Rectangle rect = new Rectangle ();
rect.Width =50;
rect.Height = 25;
Rectangle Square = new Rectangle ();
square.Height = square.Width = 40;
Console.WriteLine (rect.Height); //Output:‖25‖
Console.WriteLine (square.Width); //Output:‖40‖
rect.Height = 125;
U20CSCMO2 - C# AND NETPROGRAMMING 34
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}
READ ONLY PROPERTIES:
Example:
Public int Area

{
Get
{
return height*width;
}
}
Public int Perimeter
{
Get
{
return 2*(height + width);
}
}

7. Explain Arrays In Detail

 An Array is a data structure that contains a number of variables, which are accessed
through computed indices.

 The variables contained in an array, are called the elements of the array.
 They must all be of the same type, and this type is called the element type of the array.

U20CSCMO2 - C# AND NETPROGRAMMING 35


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
SYNTAX:int [ ] numbers;
Array on Heap:
A one-dimensional array on the heap.

int [ ] = numbers;
numbers = new int[4];
There are three steps to create an array.
1. Declaration
2. Construction/ Creation
3. Initialization
Example:
Public class ArrayTest
{
Public Static void main (String [ ] args)
{
int [ ] scores;
scores = new int [3];
scores [0] = 10;
scores [1] = 7;
scores [2] = 9;

}}
Creating an Array Declaration:
Declaring an array means providing a name and it‘s Data Type.
1. Single Declaration
2. Multiple Declaration
3. Array of Objects
Example:
Public class ArrayTest
{
Public static void Main (String [ ] args)
{
int [ ] numbers;
char [ ] letters, symbols;
string [ ] countries;
}}

U20CSCMO2 - C# AND NETPROGRAMMING 36


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Creating an Array Construction:


Constructing an array means creating an object of its declared type.
Example:
Public class Arraylist
{
Public static void Main (string [ ] args)
{
int [ ] numbers;
char [ ] letters, symbols;
string [ ] countries;
numbers = new int [3];
string [ ] currencies = new string [3];
}}

MANIPULATING ARRAYS:
Example:
Public class ArrayTest
{
Public static void Main (string [ ] args)

{
int [ ] numbers = new int [3];
numbers [0] =100;
numbers [1] =200;
numbers [2] =300;
int [ ] new Numbers = {1,2,3};
for (int i=0; i<numbers.Length; i++)
{
System.Console.WriteLine (numbers [i]);
}
numbers = new Numbers;
Sum Numbers (numbers);
Sum Number (new int [ ] {3,2,1});
}
Static void sumNumbers (int [ ] n)

U20CSCMO2 - C# AND NETPROGRAMMING 37


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
{
Int sum = 0;
For (int i=0; i<n.Length; i++)
Sum+ = n[i];
System.Console.WriteLine (Sum);
}}
Single – Dimensional Arrays are declared as
int [ ] numbers;
numbers = new int [4];
string [ ] myStringArray;
can also be initialized as,
int [ ] numbers = new int [ ] {1,3,5,7,9};
string [ ] mystringArray = new string [ ]
{“Sun”, “Sat”, “Mon”, “Tues”,”Wed”, “Fri”
}; int [ ] numbers = {1,3,5,7,9};
string [ ] mystringArray = {“Sun”, “Sat”, “Mon”, “Tues”, “Wed”, “Fri”};
Multi Dimensional Arrays are declared as
int [,] numbers;
numbers = new int [4,2];
int [, , ] numbers;

numbers = new int [4,2,3];


can also be initialized as
int [,] numbers = new int [4,2]
{ {1,2}, {3,4}, {5,6}, {7,8}};
JAGGED ARRAY:
A Jagged array is an array whose elements are arrays. The elements of a jagged array can
be different dimensions and sizes.
Jagged arrays are also known as an array of arrays.
int [ ] [ ] x = new int [3] [ ];
x[0] = new int [3];
x[1] =new int [2];
x[2] =new int [4];

U20CSCMO2 - C# AND NETPROGRAMMING 38


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Example:
Console.WriteLine (―Single Dimension Array Sample‖);
//single dim array
String [ ] strArray = new string [ ] {“Mahesh Chand”, “Mike Gold”, “Raj
Beniwal”, “Praveen Kumar”, “DhineshBeniwal”};
//Read array items using foreach loop
foreach (string str in strArray)
{
Console.WriteLine (“Multi – Dimension Array Sample”);
String [,] string2DArray = new string [2,2] { {“Rosy”, “Amy”}, {“Peter”,
“Albert”}};
foreach (string str in String2DArray)
{
Console.WriteLine (str);
}
Console.WriteLine (“……”);
Console.WriteLine (“Jagged Array Sample”);
int [ ] [ ] int Jagged Array S ={ new int [ ] {2,12}, new int [ ] {14, 14, 24, 34},
new int [ ] {6,16,26,36,46,56}};
//Loop through all items of a jagged array
for (int i=0; i<int JaggedArray3.Length; i++)
{
Console.Write (“Element ({0}:”,i);
for (int j=0; j<int JaggedArray3[i].Length; j++)
{
Console.Write (“{0}{1}”, int JaggedArray3 [i][j],
j==(int JaggedArray3[i].Length-1)?‖‖:‖‖);

U20CSCMO2 - C# AND NETPROGRAMMING 39


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}
Console.WriteLine ();
}
Console.WriteLine (“………”);

OUTPUT

Single Dimension Array Sample


Mahesh Chand
Mike Gold
Raj Beniwal
Praveen Kumar
Dinesh Beniwal

Multi – Dimension Array Sample


Rosy
Amy
Peter
Albert

Jagged Array Sample


Element (0): 2 12
Element (1): 14 14 24 34
Element (2): 6 16 26 36 46 56
4. Explain Structs In Detail. (Apr 2012)

Structures (Struct) are similar to classes. Are used for simple composite data types.Struct
keyword is used to declare structures.
Syntax:
StructStruct_name
{
data member1;
data member2;
………..
………..
………..
U20CSCMO2 - C# AND NETPROGRAMMING 40
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}
Variables are known as members or fields or elements.
Example:
Struct student
{
Public string Name;
Public intRollNumber;
Public double TotalMarks;
}
Student S1 //declare a student
S1.Name = “John”
S1.RollNumber = “0200789”
S1 is a variable type of structure student. Member variable can be accessed using dot notation.
Another Example:
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);
}}

U20CSCMO2 - C# AND NETPROGRAMMING 41


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
OUTPUT
My Point: x=0; y=0
Your Point: x=10, y =10

8. Explain Strings In Detail.


The .NET Framework System.String class represents an immutable string of characters.
Immutable because its value can‘t be modified once it‘s been created. Methods that appear to
modify a string actually return a new string containing the modification. Besides the string class,
the .NET Framework classes offer String Builder, String Format, String Collection, and so on,

Together these offer comparison, appending, inserting, conversion, copying, formatting,


indexing, joining, splitting, padding, trimming, removing, replacing and searching methods.
Consider this example, which uses Replace Insert and ToUpper.
Public class TestStringsApp
{
Public static void Main (String [ ] args)
{
String a =‖Strong‖;
String b = a.Replace (‘0‘, ‘I‘ );
Console.WriteLine (b);
String c = b.Insert (3, “engthen”);
String d = c.ToUpper ();
Console.WriteLine (d);
}}

The output from this application will be String STRENGTHENING.


String Formatting:
Both String.Format and WriteLine formatting are governed by the same formatting
Rules.
For example, the following three statements produce the same output.
Public class TestConsoleApp
{
Public static void Main (string [ ] args )
{
Console.WriteLine (123);
Console.WriteLine (“{0}”, 123);

U20CSCMO2 - C# AND NETPROGRAMMING 42


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Console.WriteLine (“{0.D3}”, 123);
}}

The output is as follows


123
123
123
We would get exactly the same results using String.Format directly.
String s = String.Format (“123”);

String t = String.Format ({0}, 123);

String u = String.Format (“{0:D3}”, 123);


Console.WriteLine (s);
Console.WriteLine (t);
Console.WriteLine (u);
Format Specifiers:
Standard Numeric Format strings are used to return strings in commonly used formats.
String and WriteLine Format Specifiers:
CHARACTER INTERPRETATION
C or c Currency
D or d Decimal
E or e Exponent
F or f Fixed Point
G or g General
N or n Number
R or r Round Trip
X or x Hex

Public class Formatspecapp


{
Public static void Main (string [ ] args)
{
int i =123456;
Console.WriteLine (“{0:C}”,i); // £123,456.00
Console.WriteLine ({0:D}”.i); //123456

U20CSCMO2 - C# AND NETPROGRAMMING 43


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Console.WriteLine (“{0:E}”.i); //1.234560E+005
Console.WriteLine (“{0:F}”.i); // 123456.00
Console.WriteLine (“{0:G}”.i); // 123456
Console.WriteLine (“{0:N}‖.i); // 123,456.00
Console.WriteLine (“{0:P}.i); // 12,345,600.00%
Console.WriteLine (“{0:X}”.i); // 1E240
}}

Objects and ToString:


Recall that all data types both predefined and user defined inherit from the system.object
class in the .NET Framework, which is aliased as object.
Public class thing
{
Public int i=2;
Public int j=3;
}
Public class objecttypeapp
{
Public static void Main ()
{
object a;
a=1;
Console.WriteLine (a);
Console.WriteLine (a.ToString ());
Console.WriteLine (a.Gettype ());
Console.WriteLine ();
Thing b = new Thing ():
Console.WriteLine (b);
Console.WriteLine (b.ToString ());
Console.WriteLine (b.Gettype ());
}}
OUTPUT:
1
1
System.Int32

U20CSCMO2 - C# AND NETPROGRAMMING 44


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
ObjectType.Thing
ObjectType.Thing
ObjectType.Thing
Numeric String Parsing:

All the basic types have tostring method, which is inherited from the object type, and all
the numeric types have a parse method, which takes the string representation of a number and
returns you its equivalent numeric value.
Public class NumParsingApp
{
Public static void Main (string [ ] args)
{
int i = int.parse (“12345”);
Console.WriteLine (“i={0}”,i); int j = Int32.Parse
(“12345”); Console.WriteLine (“j= {0}”, j);
double d = double.Parse (“1.2345E +6”);
Console.WriteLine (“d ={0:F}”, d);
String s = i.ToString ():
Console.WriteLine (“S = {0}”, S);
}}
OUTPUT
i=12345
j=12345
d=1234500.00
s=12345
Strings and Date Time:
A date time object has a property named ticks that stores the date and time as the number of 100
– nanosecond intervals.
Date and Time values are formatted using standard or custom patterns stored in the properties of
a Date Time Format Info Instance.
Encoded Strings:
The System text namespace offers an Encoding class. Encoding is an abstract class, so we
can‘t instantiate it directly. It does provide a range of methods and properties for converting
arrays and strings of Unicode characters to and from arrays of bytes encoded for a target code
page.

U20CSCMO2 - C# AND NETPROGRAMMING 45


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

The String Builder Class:


With the String class, methods that appear to modify a string actually return a new string
containing the modifications. This behavior is sometimes a nuisance because if you make several
modifications to a string, we need to end up working with several generations of copies of the
original. For this reason, string Builder class in the System.Text namespace is provided.

Splitting String:
The string class offers a split method, for splitting a string into sub strings, with the splits
determined by arbitrary separator characters that you supply to the method.

Class SplitstringsApp
{
Static void Main (String [ ] args)
{

String s =‖Once upon A Time In America‖);Char [ ] seps = new


char [ ] { ‗ ‗};
Foreach (string ss in s.Split (seps))
Console.WriteLine (ss);
}
}
OUTPUT:

Once

Upon

A
Time
In
America

Extending Strings:

In libraries before the .NET era, it became common practice to extend the string class
found in the library with enhanced features. Unfortunately, the string class in the .NET
Framework is sealed, therefore, you can‘t derive from it. On the other hand, its entirely possible

U20CSCMO2 - C# AND NETPROGRAMMING 46


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
to provide a series of encapsulated static methods that process strings.

Example:
The string class offers the TOUPPER and TOLOWER methods for converting to
uppercase or lowercase, respectively but this class does not offer a method to convert to proper
case (i.e.) Initial capitals on each word.
String Interning:
During the process of string interning, all the constant strings in an application are stored in a
common place in memory, thus eliminating unnecessary duplicates. This practice clearly saves
space at run time but can confuse the unwary.

9. What are the string handling methods? Describe. (Nov’13)


String methods:
1.clone() method
Clone() method creates and returns a copy of string object.
Syntax:
Objname.clone();
Ex:
stringstr = "Clone() Test";
stringclonedString = null;
clonedString = (String)str.Clone();
Console.WriteLine(clonedString);
2.compare() method:
Compare function compares two strings
intstring.Compare(string str1,string str2)
It returns an Integer indication lexical relationship between the two comprehends
Parameters:
string str1 : Parameter String
string str2 : Parameter String
Returns:
Integer : returns less than zero, zero or greater than zero.
Less than zero : str1 is less than str2
zero : str1 is equal to str2
Greater than zero : str1 is greater than str2
Example:

U20CSCMO2 - C# AND NETPROGRAMMING 47


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
using System;
usingSystem.Collections;

namespaceCollectionsApplication
{
class Program
{
static void Main(string[] args)
{
string str1 = null;
string str2 = null;

str1 = "csharp";
str2 = "CSharp";
int result = 0;
result = string.Compare(str1, str2);
Console.WriteLine(result);
str1 = "CSharp";
result = string.Compare(str1, str2);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
3. stringConcat

Concat in CSharp String Class Concatenates the two specified string and create a new string.
stringconcat(string str1,string str2)
String Concat method returns a new String
Parameters:
String str1 : Parameter String
String str2 : Parameter String
Returns:
String : A new String return with str1 Concat with str2
Example:
string str1 = null;

U20CSCMO2 - C# AND NETPROGRAMMING 48


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
string str2 = null;
str1 = "AHILA ";
str2 = "THANGARAJAN";

Console.WriteLine(string.Concat(str1, str2));
Console.ReadKey();

4. The CSharpContains method


It returns true if and only if this string contains the specified sequence of char values.
boolstring.containe(string str)
Parameters:
String str - input String for search
Returns:
Boolean - Yes/No
If the str Contains in the String then it returns true
If the str does not Contains in the String it returns False
For ex: "This is a Test".Contains("is") return True
"This is a Test".Contains("yes") return False
Example:
stringstr = null;
str = "CSharp TOP 10 BOOKS";
if (str.Contains("TOP") == true)
{
Console.WriteLine("Exist ");
}
else
{
Console.WriteLine("Not Exist");
}
5. string Copy
CSharp String Copy method is create a new String object with the same content
stringstring.Copy(string str)
Parameters:
String str : The argument String for Copy method
Returns:
String : Returns a new String as the same content of argument String
U20CSCMO2 - C# AND NETPROGRAMMING 49
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
Exceptions:
System.ArgumentNullException : If the argument is null.
EXAMPLE:

string str1 = null;


string str2 = null;
str1 = "AHILA";
str2 = string.Copy(str1);
Console.WriteLine(str2);

6. String Equals
This function is to check the specified two String Object values are same or not
boolstring.Equals(string str1,string str2)
Parameters:
String str1 : The String argument
String str2 : The String argument
Returns:
Boolean : Yes/No
It return the values of the two String Objects are same
For ex :
Str1 = "Equals()"
Str2 = "Equals()"
String.Equals(Str1,Str2) returns True
String.Equals(Str1.ToLower,Str2) returns False
Because the String Objects values are different
Example:
string str1 = "ANI";
string str2 = "ani";
if (string.Equals(str1, str2))
{
Console.WriteLine("Equal ");
}
else
{
Console.WriteLine("not Equal ");

U20CSCMO2 - C# AND NETPROGRAMMING 50


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
}
7. string Length
The Length property in String Class returned the number of characters occurred in a String.
intstring.length

Returns:
Integer : The number of characters in the specified String
example:
"This is a Test".Length returns 14.
Example:
stringstr = null;
str = "ahila";
Console.WriteLine(str.Length);

U20CSCMO2 - C# AND NETPROGRAMMING 51


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

U20CSCMO2 - C# AND NETPROGRAMMING 52

You might also like