C# Unit - II
C# Unit - II
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
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
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.
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.
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
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.
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.
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
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 ()
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
{
}
}
C# introduces a new concept called Indexer. This is very useful for some situation. Let us
discuss something about Indexer.
{
// set codes goes here
}}
{
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 ();
}}}
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.
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);
}}}
OUTPUT
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.
10 Marks
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
{
……
……
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
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;
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
}
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 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)
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.
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);
}
}
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.
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;
}}
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)
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)?‖‖:‖‖);
OUTPUT
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);
}}
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.
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)
{
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
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.
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;
Console.WriteLine(string.Concat(str1, str2));
Console.ReadKey();
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 ");
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);