Unit-1 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

Unit-1 Introduction

Introduction: Evolution of .NET, Overview of .NET


Framework 4.0, Exploring Visual Studio IDE, C#
Fundamentals – Identifiers and Keywords, Variables and
Constants – Value Types, Reference Types, Pointer Types,
Type Conversions, Boxing and Unboxing, Expressions and
Operators, Control Flow Statements, Exception Handling,
Exploring Namespaces, Exploring Classes and Objects and
Exploring Structs

Dr. Ch. Ram Mohan Reddy


10/7/2022 Dr. Ch. Ram Mohan Reddy 1
Execution Environment

10/7/2022 Dr. Ch. Ram Mohan Reddy 2


The .Net Framework
• The .Net Framework is the combination of layers of CLR, FCL, Data and XML Classes
and our Windows, Web applications and Web Services.

10/7/2022 Dr. Ch. Ram Mohan Reddy 3


10/7/2022 Dr. Ch. Ram Mohan Reddy 4
The Common Language Runtime (CLR)
• It is a framework layer that resides above the OS and handles the execution of all
the .NET applications.
• Our programs don’t directly communicate with the OS but go through the CLR.
• CLR is a runtime environment in which programs written in C# and other .NET
languages are executed. It also supports cross-language interoperability.
• The CLR provides a number of services that include:
• Loading and execution of programs
• Verification of type safety.
• Compilation of IL into native executable code.
• Memory Management (Automatic garbage collection)
• Enforcement of security.
• Interoperability with other systems.
• Managing exceptions and errors.

10/7/2022 Dr. Ch. Ram Mohan Reddy 5


MSIL (Microsoft Intermediate Language) Code
• When we compile our .Net Program using any .Net compliant language (such as C#,
VB.Net or C++.Net) our source code does not get converted into the executable binary
code, but to an intermediate code known as MSIL which is interpreted by the Common
Language Runtime.
• Upon program execution, this MSIL (intermediate code) is converted to binary
executable code (native code). Cross language relationships are possible as the MSIL
code is similar for each .Net language.

Just In Time Compilers (JITers)


• When our IL compiled code needs to be executed, the CLR invokes the JIT compiler,
which compile the IL code to native executable code (.exe or .dll) that is designed for the
specific machine and OS.
The Framework Class Library (FCL)
• The .Net Framework provides a huge Framework (or Base) Class Library (FCL) for common, usual
tasks. FCL contains thousands of classes to provide access to Windows API and common
functions like String Manipulation, Common Data Structures, IO, Streams, Threads, Security,
Network Programming, Windows Programming, Web Programming, Data Access, etc.
• It is simply the largest standard library ever shipped with any development environment or
programming language.
10/7/2022 Dr. Ch. Ram Mohan Reddy 6
The Common Language Specification (CLS)
• The CLS is a subset of CTS which all .NET languages are expected to support.
• It was always a dream of Microsoft to unite all different languages in to one
umbrella and CLS is one step towards that.
• Microsoft has defined CLS which are nothing but guidelines that language to follow
so that it can communicate with other .NET languages in a seamless manner.
The Common Type System (CTS)

• In order that two language communicate smoothly CLR has CTS (Common Type
System).
• Example:- In VB you have “Integer” and in C++ you have “long” these data types
are not compatible so the interfacing between them is very complicated.
• In order to able that two different languages can communicate Microsoft
introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype
in C++ will convert it to System.int32 which is datatype of CTS.
• The CTS supports a variety of types and operations found in most programming
languages and therefore calling one language from another does not require type
conversion.

10/7/2022 Dr. Ch. Ram Mohan Reddy 7


10/7/2022 Dr. Ch. Ram Mohan Reddy 8
Garbage Collection (GC)
• CLR also contains the Garbage Collector (GC), which runs in a low-priority thread
and checks for un-referenced, dynamically allocated memory space.
• If it finds some data that is no longer referenced by any variable/reference, it re-
claims it and returns it to the OS.
• The presence of a standard Garbage Collector frees the programmer from
keeping track of dangling data.
Managed Code
• Managed code runs inside the environment of CLR i.e. NET runtime. In short all IL
are managed code.
• If you are using some third party software- for Ex:- VB6 or VC++ component they
are unmanaged code as .NET runtime (CLR) does not have control over the source
code execution of the language.
Note:-
• (IL) Intermediate Language is also known as MSIL (Microsoft Intermediate
Language) or CIL (Common Intermediate Language).
• All .NET source code is compiled to IL. This IL is then converted to machine code
at the point where the software is installed, or at run-time by a Just-In-Time (JIT)
compiler.

10/7/2022 Dr. Ch. Ram Mohan Reddy 9


Example

using System;
namespace MyHelloWorldApplication {
class HelloWorld{
static void Main(string[] args){
Console.WriteLine("Hello World");
}
}
}

• Save this with any file name with the extension ".cs". Example:
’MyFirstApplication.cs’ To compile this file, go to command prompt and write:
csc MyFirstApplication.cs
• This will compile your program and create an .exe file MyFirstApplication.exe) in
the same directory and will report any errors that may occur.
• To run your program, type:
MyFirstApplication
• This will print Hello World as a result on your console screen.
• To compile and execute your application, select Debug - Start Without Debugging
or press Ctrl+F5

10/7/2022 Dr. Ch. Ram Mohan Reddy 10


Creating a Simple C# Console Application
Getting Command-Line Input: NamedWelcome.cs Getting Interactive Input: InteractiveWelcome.cs
// Namespace Declaration // Namespace Declaration
using System; using System;
// Program start class // Program start class
class NamedWelcome { class InteractiveWelcome {
// Main begins program execution. // Main begins program execution.
static void Main(string[] args) { public static void Main()
// Write to console {
Console.WriteLine("Hello, {0}!", args[0]); // Write to console/get input
Console.WriteLine("Welcome to BMSCE, MCA !"); Console.Write("What is your name?: ");
} Console.Write("Hello, {0}! ", Console.ReadLine());
} Console.WriteLine(" Welcome to BMSCE, MCA!");
}
}
Sample code-
int answer = 42; string greeting = "Hello, World!"; double bigNumber = 1e100;
System.Console.WriteLine("{0} {1} {2}", answer, greeting, bigNumber);
Once installed, the compiler will need to be run from a command prompt window. The compiler
executable is called CSC.EXE and by default it is not in the command path. Find where CSC.EXE is installed
on your system (in .NET Framework 3.5 on Windows XP it is installed in the
\WINDOWS\Microsoft.NET\Framework\v3.5) by performing a Search of your disk drives. Once the
location has been ascertained, add the location to the path environment variable:
Set PATH=%PATH%;%Windir%\Microsoft.NET\Framework\v3.5
1. csc Filename.cs
2. Filename
10/7/2022 Dr. Ch. Ram Mohan Reddy 11
What is ADO.NET

• ADO.NET is not a different technology. In simple terms, you can think of ADO.NET
as a set of Classes (Framework), that can be used to interact with data sources
like Databases and XML Files.
• This data can, then be consumed in any .NET application.
• ADO stands for Microsoft ActiveX Data Objects.

• The following are, a few of the different types of .NET applications that use
ADO.NET to Connect to a database, execute commands, and retrieve data.

• ASP.NET Web Applications


• Windows Applications
• Console Applications

Dot Net Data Providers:


• Data Provider for SQL Server – System.Data.SqlClient
• Data Provider for Oracle – System.Data.OracleClient
• Data Provider for OLEDB – System.Data.OleDb
• Data Provider for ODBC – System.Data.Odbc

10/7/2022 Dr. Ch. Ram Mohan Reddy 12


What is LINQ
• LINQ stands for Language Integrated Query.
• LINQ enables us to query any type of data store (SQL Server, XML documents, Object
in memory etc.)
Why should we use LINQ LINQ Architecture

• LINQ enables us to work with different data sources using a similar coding style without
having the need to know the syntax specific to the data source. Another benefit of using
LINQ is that it provides intellisense and compile time error checking.
• LINQ query can be written using any .NET supported programming language.
• LINQ provider is a component between the LINQ query and the actual data source, which
converts the LINQ query into a format that the underlying data source can understand.
• For example LINQ to SQL provider converts a LINQ query to T-SQL that SQL Server
database can understand.

10/7/2022 Dr. Ch. Ram Mohan Reddy 13


Points to remember

1. IL is also called as MSIL, CIL, Managed Code.


2. Assemblies have an extension of .DLL or .EXE depending on the type of
application.
3. .NET assemblies contain IL, where as pre .NET assemblies contain Native
code (Machine code)
4. .NET the application execution consists of 2 steps (offers application
portability)
1) Compilation – Source code to IL
II) Execution or JIT compilation – IL to platform specific native code
5. CLR - .NET runtime environment provides several benefits. Garbage collection
is one of them.
6. .NET supports different programming languages like C#, VB, J# and C++, C#,
VB and J# can only generate managed code (IL), where as C++ can generate
both managed code (IL) and un-managed code (Native code).
7. The native code is not stored permanently anywhere, after we close the
program the native code is thrown away. . When we execute the program
again, the native code gets generated again.

10/7/2022 Dr. Ch. Ram Mohan Reddy 14


1. What is .NET Framework?

.NET Framework is a platform, which helps in developing portable, scalable, and robust
applications. It enables you to create the applications by integrating different
programming languages, such as C#, VB, J#, and Visual C++. .NET Framework supports
the object-oriented programming model for multiple languages. You can develop, run,
and deploy the following applications:
• Windows Forms applications
• Console Applications
• WPF
• Web applications (ASP.NET applications)
• Web services
• Windows services
• Service-oriented applications using WCF
• Workflow-enabled applications using WF
• .NET enables creation of sharable components used in the distributed
computing architecture

10/7/2022 Dr. Ch. Ram Mohan Reddy 15


2. Explain the benefits of .NET Framework.
• Consistent programming model – provides a consistent object-oriented programming model
across different languages.
• Cross-platform support – specifies that any windows platform that supports CLR can execute
.NET application.
• Language interoperability – Enables code written in different languages to interact with each
other.
- Allows reusability of code and improves the efficiency of the development process.
• Automatic Management of Resources- CLR automatically tracks the resource usage ( free
application resources, such as files, memory, network and database connections)
• Ease of Deployment - .NET framework installs applications or components that do not affect
the existing applications.

3. Briefly describe the roles of CLR in .NET Framework.


CLR is one of the most important components of .NET Framework. It provides a runtime
environment to run the code and various services to develop the applications easily.
Some of the services provided by CLR are as follows:
• Automatic memory management
• Garbage collection
• CAS—It is the CLR’s security system that enforces security policies by preventing unauthorized
access to protected resources and operations. CAS also helps in making the code robust, which
implies that it makes the code extensible and reusable.
• Code Verifications—CLR imposes type safety and prevents the source code from performing
illegal operations, such as accessing invalid memory locations.
10/7/2022 Dr. Ch. Ram Mohan Reddy 16
4. Explain the CTS
• CTS is a component of CLR, which contains certain guidelines for declaring, using,
and managing types at runtime.
5. What is CLS?
CLS is a set of basic rules, which enables interoperability between two .NET-
compliant languages.
6. Describe the managed code?
Managed code is the code that is executed directly by the CLR. The applications that
are created using managed code automatically have CLR services, such as type
checking, security, and automatic garbage collection.
7. Explain the differences between managed and unmanaged code.
Managed code is the code that is executed directly by the CLR instead of the
operating system.
Unmanaged code directly compiles to the machine code and runs on the machine
where it has been compiled.
The applications that are created using managed code automatically have CLR
services, which help in providing platform and language independence to managed
code applications. On the other hand, unmanaged code does not have services such
as security or memory management; therefore, developers have to take care of
these services.
10/7/2022 Dr. Ch. Ram Mohan Reddy 17
8. What is Assembly? Briefly give the contents of assembly manifest.
An assembly is the primary building block of .NET Framework applications. Every .NET
application compiles into an assembly, which is stored in a CLR PE file. An assembly
contains a self-describing binary file that can be either DLL or EXE. It also contains a
collection of types, such as classes, interfaces, and structures. A single assembly can
contain multiple code files or a single code file can have more than one assembly.
Assemblies can be of two types: static or dynamic. Static assemblies include
interfaces, classes, and resources. These assemblies are stored in the PE files on a
disk. On the other hand, dynamic assemblies run directly from the memory without
being saved to a disk before execution.
9. What is ADO.NET? Describe the features of ADO.NET.
ADO.NET as a set of Classes (Framework), that can be used to interact with data
sources like Databases and XML Files.

10/7/2022 Dr. Ch. Ram Mohan Reddy 18


Using Keywords as Identifiers in C#.NET
Identifiers
• An identifier is a name used to identify a class, variable, function, or any other user-defined item.
• The basic rules for naming classes in C# are as follows:
• A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore.
• The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' /
and \.
• However, an underscore ( _ ) can be used.
• It should not be a C# keyword.
In C# We cannot use a Keywords as an Identifier since the former is predefined and has special
meaning to the compiler whereas an identifier is user-defined.
However, we can use a keyword as user-defined identifier by appending "@" (at) or "_"
(underscore) characters.

For example: if we write


Class class //Conflict error
It throws an error. Here we can place @ or _(underscore) before class to use it as class name.
Class @class / _class //No error

In the same way we can also write as


int @class;
@class = 5;
Like this we can use @class or _class as identifier.
10/7/2022 Dr. Ch. Ram Mohan Reddy 19
C# Keywords
• Keywords are reserved words predefined to the C# compiler.
• These keywords cannot be used as identifiers.
• However, if you want to use these keywords as identifiers, you may prefix the keyword with the
@ character.

10/7/2022 Dr. Ch. Ram Mohan Reddy 20


Built-in Data Types
• C# is a strongly-typed language. Before a value can be stored in a variable, the type of the
variable must be specified
Data Type Range

byte 0 .. 255
sbyte -128 .. 127
short -32,768 .. 32,767
ushort 0 .. 65,535
int -2,147,483,648 .. 2,147,483,647
uint 0 .. 4,294,967,295
long -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807
ulong 0 .. 18,446,744,073,709,551,615
float -3.402823e38 .. 3.402823e38
double -1.79769313486232e308 .. 1.79769313486232e308

decimal -79228162514264337593543950335 .. 79228162514264337593543950335


char A Unicode character.
string A string of Unicode characters.
bool True or False.
10/7/2022
object An object. Dr. Ch. Ram Mohan Reddy 21
10/7/2022 Dr. Ch. Ram Mohan Reddy 22
10/7/2022 Dr. Ch. Ram Mohan Reddy 23
Variables and Constants
• A variable represents a numeric or string value or an object of a class. The value that the variable
stores may change, but the name stays the same. A variable is one type of field.
Ex:-1 int x = 1; // x holds the value 1
x = 2; // now x holds the value 2
Ex:-2 int answer = 42;
string greeting = "Hello, World!";
double bigNumber = 1e100;
System.Console.WriteLine("{0} {1} {2}", answer, greeting, bigNumber);
• A constant is another type of field. It holds a value that is assigned when the program is compiled,
and never changes after that.
• Constants are declared using the const keyword; they are useful for making your code more legible.
Ex:-3 const int speedLimit = 55;
const double pi = 3.14159265358979323846264338327950;

10/7/2022 Dr. Ch. Ram Mohan Reddy 24


Value Types, Reference Types
• A data type is a value type if it holds the data within its own memory allocation. A reference
type contains a pointer to another memory location that holds the data.
• All the data types in .net are classified in to value types and reference types.
• The data types whose values are directly stored in stack memory area are called as value types
and the data types whose values are stored in heap memory area and its address is stored in a
variable in stack memory area are called as reference types.
• Among all built in data types of .net string and object are reference type and all other data
types are value types.
• Among user defined data types, class, interface, delegate and arrays are reference type while
structure and enumeration are value type.
Value Types
----------------
Value types include the following:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte,
UShort, UInteger, or ULong
Reference Types
----------------------
Reference types include the following:
String
All arrays, even if their elements are value types
Class types
Delegates
10/7/2022 Dr. Ch. Ram Mohan Reddy 25
Boxing and unboxing
• Boxing and unboxing is an important concept in C# type system. With Boxing and unboxing one
can link between value-types and reference-types by allowing any value of a value-type to be
converted to and from type object.
Boxing
• Boxing is a mechanism in which value type is converted into reference type.
• It is implicit conversion process in which object type (super type) is used.
• In this process type and value both are stored in object type
Unboxing
• Unboxing is a mechanism in which reference type is converted into value.
• It is explicit conversion process.
Program to show boxing and unboxing:
using System;
namespace boxing {
class Program {
static void Main(string[] args) {
int i = 10;
object o = i; // boxing
int j = (int)o; // unboxing
Console.WriteLine("value of o object : " + o);
Console.WriteLine("Value of j : " + j);
Console.ReadLine();
}
}
}
10/7/2022 Dr. Ch. Ram Mohan Reddy 26
Boxing and unboxing,
• Converting value type to reference type is called boxing and converting reference type to value type
is called as unboxing.
• Boxing and unboxing are only the technical terms for type casting from value type to reference type
and vice versa.
• Access to value types will be fast when compared to reference types. Because they directly contain
the value and no need to refer another memory location.
Ex:-
int i = 67; // i is a value type
object o = i; // i is boxed
System.Console.WriteLine(i.ToString()); // i is boxed
Ex:-
System.Collections.ArrayList list = new System.Collections.ArrayList(); // list is a reference type
int n = 67; // n is a value type
list.Add(n); // n is boxed
n = (int)list[0]; // list[0] is unboxed
• It is recommended to avoid boxing and unboxing in the program wherever it is possible. Because
these operations take time and will affect the performance of the application.
Ex:- int AddTen(int number) // parameter is passed by value
{
return number + 10;
}
Ex:- void AddTen(ref int number) // parameter is passed by reference
{
number += 10;
}
Using the ref keyword. This is the C# equivalent of the C++ technique of passing a pointer to a variable into a
function. As with the C++ version, the method has the ability to change the contents of the variable, which may
10/7/2022 Dr. Ch. Ram Mohan Reddy 27
not always be safe. The programmer needs to decide on the trade-off between security and performance.
Type Conversions
Type conversion is converting one type of data to another type. It is also known as Type Casting. In
C#, type casting has two forms:
• Implicit type conversion - These conversions are performed by C# in a type-safe manner. For
example, are conversions from smaller to larger integral types and conversions from derived
classes to base classes.
• Explicit type conversion - These conversions are done explicitly by users using the pre-defined
functions. Explicit conversions require a cast operator.
using System;
namespace TypeConversionApplication {
class ExplicitConversion {
static void Main(string[] args) {
double d = 5673.74;
int i;
// cast double to int.
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
Output - 5673

10/7/2022 Dr. Ch. Ram Mohan Reddy 28


C# Type Conversion Methods
Sr.No Methods & Description
1 ToBoolean - Converts a type to a Boolean value, where possible.
2 ToByte - Converts a type to a byte.
3 ToChar - Converts a type to a single Unicode character, where possible.
4 ToDateTime - Converts a type (integer or string type) to date-time structures.
5 ToDecimal - Converts a floating point or integer type to a decimal type.
6 ToDouble - Converts a type to a double type.
7 ToInt16 - Converts a type to a 16-bit integer.
8 ToInt32 - Converts a type to a 32-bit integer. using System;
namespace TypeConversionApplication{
9 ToInt64 - Converts a type to a 64-bit integer. class StringConversion {
10 ToSbyte - Converts a type to a signed byte type. static void Main(string[] args) {
int i = 75;
11 ToSingle - Converts a type to a small floating point number. float f = 53.005f;
12 ToString - Converts a type to a string. double d = 2345.7652;
bool b = true;
13 ToType - Converts a type to a specified type.
14 ToUInt16 - Converts a type to an unsigned int type. Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
15 ToUInt32 - Converts a type to an unsigned long type. Console.WriteLine(d.ToString());
16 ToUInt64 - Converts a type to an unsigned big integer. Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
Output-
75
53.005
2345.7652
10/7/2022 Dr. Ch. Ram Mohan Reddy True 29
Operators and Expressions
• Operator is an operation performed over data at runtime
➢ Takes one or more arguments (operands)
➢ Produces a new value
• Operators have precedence
➢ Precedence defines which will be evaluated first
• Expressions are sequences of operators and operands that are evaluated to a
single value.
• Operators in C#:
➢ Unary – take one operand
➢ Binary – take two operands
➢ Ternary (?: ) – takes three operands
• Except for the assignment operators, all binary operators are left-associative
• The assignment operators and the conditional operator (?: ) are right-
associative.
Category Operators
arithmetic -, +, *, /, %, ++, --
logical &&, ||, !, ^
binary &, |, ^, ~, <<, >>
comparison ==,!=, >, <, >=, <=
assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
string concatenation +
type conversion (type), as, is, typeof, sizeof
other ., new, (), [], ?:, ??

10/7/2022 Dr. Ch. Ram Mohan Reddy 30


Operator Precedence
Priority Operators
Highest priority (, )
++, -- (as postfix), new, (type), typeof,
sizeof
++, -- (as prefix), +, - (unary), !, ~
*, /, %
+ (string concatenation)
+, -
<<, >>
… <, >, <=, >=, is, as
==, !=
&, ^, |
&&
||
?:, ??

Lowest priority =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=

• Parenthesis operator always has highest precedence


• Note: prefer using parenthesis, even when it seems stupid to do so

10/7/2022 Dr. Ch. Ram Mohan Reddy 31


String Concatenation
• String concatenation operator + is used to concatenate strings
• If the second operand is not a string, it is converted to string automatically.
int a = 5;
int b = 7;

string sum = "Sum = " + (a + b);


Console.WriteLine(sum);

Console.WriteLine(
"Perimeter = " + 2 * (a + b) + ". Area = " + (a * b) + ".");
Sum = 12
Perimeter = 24. Area = 35.
• Member access operator . Is used to access object members.
• Square brackets [] are used with arrays indexers and attributes.
• Parenthesis ( ) are used to override the default operator precendence
• Class cast operator (type) is used to cast one compatible type to another.
Conditional operator ?: has the form b ? X : y
( if b is true then the result is x else the result is y)
• The new operator is used to create new objects
• The typeof operator returns System.Type object (the reflection of a type)
• The is operator checks if an object is compatible with given type.
10/7/2022 Dr. Ch. Ram Mohan Reddy 32
Expressions
• Expressions are sequences of operators, literals and variables that are calculated to a
value of some type (number, string, object or other type)
int r = (150-20) / 2 + 5;

// Expression for calculating the surface of the circle


double surface = Math.PI * r * r;

// Expression for calculating the perimeter of the circle


double perimeter = 2 * Math.PI * r; 70
15393.80400259
Console.WriteLine(r); 439.822971502571
Console.WriteLine(surface);
Console.WriteLine(perimeter);

Expressions, Data Types and Operator Priorities


• When writing expressions, the data types and the behavior of the used operators
should be considered. Ignoring this can lead to unexpected results.
// First example
double d = 1 / 2;
Console.WriteLine(d); // 0, not 0.5

// Second example
double half = (double)1 / 2;
Console.WriteLine(half); // 0.5
10/7/2022 Dr. Ch. Ram Mohan Reddy 33
null coalescing operator (??)
• The ?? operator is called the null-coalescing operator. mostly used with the
nullable value types and reference types.
• It returns the left-hand operand if the operand is not null; otherwise it returns
the right hand operand.
The following are the advantages of the Null-Coalescing Operator (??) operator:
• It is used to define a default value for a nullable item (for both value types and
reference types).
• It prevents the runtime InvalidOperationException exception.
• It helps us to remove many redundant "if" conditions.
• It works for both reference types and value types.
• The code becomes well-organized and readable.
using System;
class NullCoalesce {
static void Main() {
int? x = null;
int y = x ?? 99;
Console.WriteLine("The Value of 'Y' is:" + y);
string message = "Operator Test";
//string message = null;
string resultMessage = message ?? "Original message is null";
Console.WriteLine("The value of result message is:" + resultMessage);
10/7/2022} Dr. Ch. Ram Mohan Reddy 34
}
null coalescing operator (??) contd.,
using System;
namespace NullCoalescing {
class Program {
static void Main(string[] args) {
int? i = null; //Nullable variable
int? j = 30; //Nullable variable
int k;
k = i ?? 25; //Using ?? operator to check for null values
Console.WriteLine("The value of k is " + k);
k = j ?? 25; //Using ?? operator to check for null values
Console.WriteLine("Now the value of k is " + k);
Console.ReadLine();
}
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 35


• A nullable type can represent a value that can be undefined or from the type's
domain.
• We can use the ?? operator to return an appropriate value when the left operand
has a nullable type.
• If we try to assign a nullable value type to a non-nullable value type without using
the ?? operator, we will get a compile-time error and if we forcefully cast it, an
InvalidOperationException exception will be thrown.

• The ?? operator works for both reference types and value types. In the preceding
example y is an integer (value type) and returnMessage is a string type (reference
type).
• Use Null- Coalescing Operator (??) operator with LINQ
The ?? operator can be useful in scenarios where we deal with raw XML and the XML
shapes are irregular and/or missing elements/attributes.
10/7/2022 Dr. Ch. Ram Mohan Reddy 36
Using the :: (Scope Resolution) operator
• The :: (scope resolution) operator is added between two identifiers to define their scope.
• The left-hand identifier of the :: operator is taken as a global identifier, an extern, or alias.
• When the left-hand identifier of the :: operator is global, the global namespace is searched
for the right-hand identifier.
namespace AliasClass {
class Program {
public class System {
public void Print() {
global::System.Console.WriteLine("This is an example of :: operator");
} }
// Define a constant 'Console'
const string Console = "Hello";
const string str1 = "World";
static void Main(string[] args) {
System sys = new System();
sys.Print();
global::System.Console.WriteLine(Console);
global::System.Console.WriteLine(str1);
global::System.Console.ReadLine();
}
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 38


Using the is and as operators
The is operator checks whether an object is compatible with the given type or not and returns
a Boolean result. i.e., either true or false.
The object may either be of the same type or may be derived from that particular given type.
The as operator converts the reference types explicitly into a specific type. If the reference
type is compatible with the specified type, it performs successful conversion; otherwise, it
returns the null value.
Note - The as operator does not throw an exception.
using System;
namespace IsandAs{
class Program {
static void Main(string[] args) {
object i = 25;
object str = "Kogent Learning Solutions";
if (i is string) //Checking compatibility
Console.WriteLine("i is a string type");
else
Console.WriteLine("i is an integer type");
string str1 = i as string; //Casting i to string
string str2 = str as string; //Casting str to string
Console.WriteLine("The value of str1 is " + str1);
Console.WriteLine("The value of str2 is " + str2);
Console.ReadLine();
}
}
} 10/7/2022 Dr. Ch. Ram Mohan Reddy 39
Control Flow Statements
• Decision making structures requires the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
• Following is the general from of a typical decision making structure found in most of
the programming languages:
Statement Description

if statement An if statement consists of a boolean expression followed by


one or more statements.
An if statement can be followed by an optional else
if...else statement statement , which executes when the boolean expression is
false.
nested if statements You can use one if or else if statement inside another if or
else if statement(s).

switch statement A switch statement allows a variable to be tested for equality


against a list of values.
nested switch statements You can use one switch statement inside another switch
statement(s).

10/7/2022 Dr. Ch. Ram Mohan Reddy 40


The ? : Operator:
Conditional operator ? : ican be used to replace if...else statements.
It has the following general form:
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of
the colon.
• The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true,
then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is
false, then Exp3 is evaluated and its value becomes the value of the expression.

Loop Control Statements


• Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
• C# provides the following control statements.

Cont rol St at ement Description

break st at ement Term inates the loop or swit ch statem ent and transfers execution
to the statem ent imm ediately following the loop or switch.
cont inue st at ement Causes the loop to skip the remainder of its body and imm ediately
retest its condition prior to reiterating.

10/7/2022 Dr. Ch. Ram Mohan Reddy 41


• Programming languages provide various control structures that allow for more
complicated execution paths.
• A loop statement allows us to execute a statement or a group of statements multiple
times and following is the general from of a loop statement in most of the
programming languages:
• C# provides following types of loop to handle looping requirements.
Loop Type Description

It repeats a statement or a group of statements while a given


while loop condition is true. It tests the condition before executing the loop
body.
for loop It executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
do...while loop It is similar to a while statement, except that it tests the condition
at the end of the loop body

nested loops You can use one or more loop inside any another while, for or
do..while loop.

10/7/2022 Dr. Ch. Ram Mohan Reddy 42


The foreach Loop
• A foreach loop is used to iterate through the items in a list. It operates on arrays or
collections such as ArrayList, which can be found in the System.Collections
namespace.
• The syntax of a foreach loop is
foreach (<type> <iteration variable> in <list>) {
<statements> }.
• The type is the type of item contained in the list. For example, if the type of the list
was int[] then the type would be int.
• The iteration variable is an identifier that you choose, which could be anything but
should be meaningful. For example, if the list contained an array of people's ages,
then a meaningful name for item name would be age.
• The in keyword is required.
using System;
class ForEachLoop {
public static void Main() {
string[] names = { "Cheryl", "Joe", "Matt", "Robert" };
foreach (string person in names) {
Console.WriteLine("{0} ", person);
}
}
}
10/7/2022 Dr. Ch. Ram Mohan Reddy 43
Quick Revise
Q1. The + operator can be used as a unary operator as well as a binary operator. (True/False)
Ans. True, depending on the context of the operator, + can be used as a unary or as a binary
operator.
Q2. The unsafe keyword defines an unsafe context where you are free to use pointers.
(True/False)
Ans. True, C# allows you to use pointers in an unsafe context.
Q3. What is the value of A in the following expression?
int A= -5 * 20 % 3 – 7 + 2 * 5;
a. –30 b. 2 c. 4 d. –4
Ans. 2.
Q4. Value Types are stored on the __________, while Reference Types are stored on the
__________.
Ans. Stack, heap or managed heap.
Q5. C# uses a __________ to store the values.
Ans. Variable.
Q6. What are the two types of the variable scope?
Ans. The two types of variable scope are block scope and class scope.
Q7. What are boxing and unboxing?
Ans. Boxing and unboxing are used to create a link between the two major data types in C#:
Value Types and Reference Types. Boxing is a process of converting the Value Type into
Reference Type whereas unboxing converts the Reference Type to Value Type.

10/7/2022 Dr. Ch. Ram Mohan Reddy 44


Namespaces:-
• Namespaces are used to organize your programs.
• They also provide assistance in avoiding name clashes.
using System;
using ProjectA.TeamA;
class program {
public static void Main(){
// Console.WriteLine ("Hello");
ClassA.Print();
ProjectA.TeamB.ClassA.Print();
}
}
namespace ProjectA{
namespace TeamA {
class ClassA {
public static void Print() {
Console.WriteLine("Team A Print Method");
}
}
}
}
namespace ProjectA{
namespace TeamB {
class ClassA {
public static void Print() {
Console.WriteLine("Team B Print Method");
}
}
}
10/7/2022 } Dr. Ch. Ram Mohan Reddy 45
using System;
using PATA = ProjectA.TeamA;
using PATB = ProjectA.TeamB;
class program {
public static void Main() {
// Console.WriteLine ("Hello");
PATA.ClassA.Print();
PATB.ClassA.Print();
} }
namespace ProjectA {
namespace TeamA {
class ClassA {
public static void Print()
{
Console.WriteLine("Team A Print Method");
} } } }
namespace ProjectA {
namespace TeamB {
class ClassA {
public static void Print() {
Console.WriteLine("Team B Print Method");
} } } }

• Namespaces don’t correspond to file, directory or assembly names. They could be written in separate
files and/or separate assemblies and still belong to the same namespace.
Namespaces can be nested in2 ways.
• Namespace alias directives. Sometime you may encounter a long namespace and wish to have it
shorter. This could improve readability and still avoid name clashes with similarly named methods.
10/7/2022 Dr. Ch. Ram Mohan Reddy 46
The System Namespace
The following are some of the common namespaces provided by the .NET Framework
class library:
• System—Contains the important base classes that allow you to work with commonly-
used data types, events, event handlers, interfaces, attributes, and exceptions.
• System.Collections—Includes interfaces and classes that define various collections of
objects, including lists, queues, arrays, hash tables, and dictionaries.
• System.Data—Includes all important classes that allow you to implement data-binding
with multiple distributed data sources.
• System.Data.OleDb—Includes classes that support the OLE DB .NET data provider.
• System.Data.SqlClient—Includes classes that support the SQL Server .NET data
provider.
• System.Data.OracleClient—Includes classes to implement the data provider for
Oracle.
• System.Data.Odbc—Includes classes to implement the data provider for Open
Database Connectivity (ODBC).
• System.Diagnostics—Includes classes that allow you to debug your application and to
step through your code while debugging it. It also includes methods to start system
processes, read and write in event logs, and monitor system performance.
• System.Drawing—Provides access to the GDI+ graphics functionality. More advanced
functionality is provided in the System.Drawing.Drawing2D,
System.Drawing.Imaging, and System.Drawing.Text namespaces.
10/7/2022 Dr. Ch. Ram Mohan Reddy 47

The System Namespace., contd
• System.Drawing.Drawing2D—Includes classes that support advanced two-dimensional
and vector graphics.
• System.Drawing.Imaging—Includes classes that support advanced GDI+ imaging.
• System.Drawing.Printing—Includes classes that print related services for applications.
• System.Drawing.Text—Contains classes that help you to work with advanced GDI+
typography operations. Users can also create and use collections of fonts, by using these
classes.
• System.Dynamic—Includes classes that are used to support Dynamic Language Runtime
(DLR).
• System.Globalization—Includes classes that specify culture-related information
including the language, country/region, calendars, format patterns for dates, currency,
and numbers.
• System.IO—Includes types that support synchronous and asynchronous reading from
and writing to data streams and files.
• System.Linq— Includes classes that allow you to use Language Integrated Queries in
your applications.
• System.Messaging—Provides classes that help you to control the transmission of
message queues on the network.
• System.Net—Provides a simple programming interface to many of the protocols used on
the Internet.
• System.Net.Sockets—Includes classes that support the Windows Sockets interface. If
you have worked with the Winsock
10/7/2022 Dr. Ch.API, you Reddy
Ram Mohan should be able to develop applications
48
using the Socket class.
Creating a class and object
• A class is a construct that enables you to create your own custom types by grouping together
variables of other types, methods and events.
• A class is like a blueprint. It defines the data and behavior of a type.
public class Customer
{
//Fields, properties, methods and events go here...
}
• An object is a concrete entity based on a class, and is sometimes referred to as an instance of a
class.
• Objects can be created by using the new keyword followed by the name of the class that the
object will be based on, like this: Customer object1 = new Customer();

<access specifier> class class_name {


// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) { // method body }
<access specifier> <return type> method2(parameter_list) { // method body } ...
<access specifier> <return type> methodN(parameter_list) { // method body }
}
10/7/2022 Dr. Ch. Ram Mohan Reddy 52
using System;
namespace BoxApplication {
class Box {
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
class Boxtester {
static void Main(string[] args) {
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
} }
10/7/2022 Dr. Ch. Ram Mohan Reddy 53
Use of this keyword in C#
• The keyword "this" in C# is used to access the field variables. All the field variables
must be accessed using "this" keyword.
• It is useful when the field variable and the local variables of a method have same
name.
using System;
class Demo {
int a = 2, b = 10;
public void Get() {
int a = 23, b = 34;
Console.WriteLine("a={0} b={1}", this.a, this.b);
Console.WriteLine("It is the class variable");
Console.WriteLine("Now the local variables are:");
Console.WriteLine("a={0} b={1}", a, b);
}
}
class MainClass {
static void Main(string[] args) {
Demo d = new Demo();
d.Get();
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 54


Creating an Array of Objects
• Array of objects in C# are a little different from object arrays in C++ or java.
• First create an array and then the individual elements of the array.
• In C#, you cannot create an array and its individual methods simultaneously.
using System; class Employee {
namespace MyArrayOfObjects { string Name;
class Program { float Age;
static void Main(string[] args) { public void GetData() {
const int Size = 3; Console.Write("Enter Name :");
Employee[] Manager = new Employee[Size]; Name = (Console.ReadLine());
for (int i = 0; i < Size; i++) { Console.Write("Enter Age:");
Manager[i] = new Employee(); Age = float.Parse(Console.ReadLine());
} }
for (int i = 0; i < Size; i++) { public void PutData() {
Console.WriteLine("Details of Manager:" + (i + 1)); Console.WriteLine("The Name is:" + Name);
Manager[i].GetData(); Console.WriteLine("The Age is:" + Age);
Console.WriteLine("--------------------"); }
} }
for (int i = 0; i < Size; i++) { }
Console.WriteLine("Manager:" + (i + 1));
Manager[i].PutData();
Console.WriteLine("-------------");
}
Console.Write("\nPress ENTER to quit...");
Console.ReadLine();
}
}
10/7/2022 Dr. Ch. Ram Mohan Reddy 55
Using the Nested Classes
• A nested class is a class that is defined inside another class.
• This class acts as the member of the parent class in which it is defined.
• A nested class has the advantage of accessing all the members of its outer class.
using System;
namespace MyNestedClass{
public class Outer{
public Outer(int num) {
Number = num;
}
public class Inner {
public void DisplayNumber(Outer o)
{
Console.WriteLine("The Number is: " + o.Number);
Console.Write("\nPress Enter to quit...");
Console.ReadLine();
}
}
private int Number;
}
public class Nesting {
static void Main() {
Outer o1 = new Outer(100);
Outer.Inner i1 = new Outer.Inner();
i1.DisplayNumber(o1);
}
} }
10/7/2022 Dr. Ch. Ram Mohan Reddy 56
Defining partial classes and Methods
• When working on large projects, spreading a class over separate files enables multiple
programmers to work on it at the same time.
• When working with automatically generated source, code can be added to the class without
having to recreate the source file. Visual Studio uses this approach when it creates Windows
Forms, Web service wrapper code, and so on. You can create code that uses these classes
without having to modify the file created by Visual Studio.

public partial class Employee{


public void DoWork() {
}
}
public partial class Employee{
public void GoToLunch() {
}
}

• The partial keyword indicates that other parts of the class, struct, or interface can be defined in
the namespace. All the parts must use the partial keyword.
• All the parts must be available at compile time to form the final type. All the parts must have
the same accessibility, such as public, private, and so on.

10/7/2022 Dr. Ch. Ram Mohan Reddy 57


In Class1.cs File In Class2.cs File
Using System; Using System;
public partial class clsMAths { public partial class clsMAths {
public void Add(int k, int l) { public void Mul(int k, int l) {
Console.WriteLine("Output is {0}", k + l); Console.WriteLine("Output is {0}", k * l);
} }
public void Sub(int k, int l) { public void Div(int k, int l) {
Console.WriteLine("Output is {0}", k - l); Console.WriteLine("Output is {0}", k / l);
} }
} }

class sample{
static void Main(string[] args) {
clsMAths obj = new clsMAths();
obj.Add(5, 4);
obj.Sub(27, 9);
obj.Mul(9, 3);
obj.Div(72, 2);
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 58


Defining partial classes and Methods
• A partial method has its signature defined in one part of a partial type, and its implementation
defined in another part of the type.
• Partial methods enable class designers to provide method hooks, similar to event handlers,
that developers may decide to implement or not.
• If the developer does not supply an implementation, the compiler removes the signature at
compile time.
The following conditions apply to partial methods:
• Signatures in both parts of the partial type must match.
• The method must return void.
• No access modifiers are allowed. Partial methods are implicitly private.

namespace PM {
partial class A {
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A {
// Comment out this method and the program
// will still compile.
partial void OnSomethingHappened(String s) {
Console.WriteLine("Something happened: {0}", s);
}
}
}
10/7/2022 Dr. Ch. Ram Mohan Reddy 59
Method parameter types

Value parameters:
• creates a copy of the parameter passed, so modification does not affect each other.
Reference parameters:
• The ref method parameter keyword on a method Parameter causes a method to refer
to the same variable that was passed into the method.
• Any changes made to the parameter in the method will be reflected in that variable
when control passes back to the calling method.
Out parameters:
• use when you want a method to return more than one Value.
Parameter Arrays:
• The params keyword lets you specify a method Parameter that takes a variable number
of arguments or an array or no Arguments.
• Params keyword should be the last one in a method declaration, and only One params
keyword is permitted in a method declaration.

10/7/2022 Dr. Ch. Ram Mohan Reddy 60


// Call by value // Call by reference
using System; using System;
class progam{ class progam{
public static void Main() { public static void Main() {
int i = 0; int i = 0;
simplemethod(i); simplemethod(ref i);
Console.WriteLine(i); Console.WriteLine(i);
} }
public static void simplemethod(int j) { public static void simplemethod(ref int j) {
j = 101; j = 101;

} }
} }

10/7/2022 Dr. Ch. Ram Mohan Reddy 61


// using out parameter
using System;
class program
public static void Main() {
int Total = 0;
int Product = 0;
Calculate(10, 20, out Total, out Product);
Console.WriteLine("Sum = {0} && Product = {1}",Total, Product); }
public static void Calculate(int FN, int SN, out int Sum, out int Product) {
Sum = FN + SN;
Product = FN*SN;
} }
// Using params parameter
using System;
class program {
public static void Main() {
int[] Numbers = new int[3];
Numbers[0] = 101;
Numbers[1] = 102;
Numbers[2] = 103;
ParamsMethod();
// ParamsMethod(Numbers);
// ParamsMethod(1, 2, 3, 4, 5); }
public static void ParamsMethod(params int[] Numbers) { // Instead params replace int
Console.WriteLine("There are {0} elements", Numbers.Length);
foreach (int i in Numbers) {
Console.WriteLine(i);
} } }
10/7/2022 Dr. Ch. Ram Mohan Reddy 62
Returning a Value from a Method
• A method can return a value to the caller of the method.
• If the return type is void, then the method will not return any value.
• However, if the return type is other than void, such as int, double or string, then the
method can return a value using the return keyword.
• A statement with the return keyword compares the return type of the method with
the return value and if they match, it returns a value to the caller method.
using System;
namespace MyReturnValue{
class Program {
static void Main(string[] args){
MyArea myarea = new MyArea();
myarea.RectArea();
Console.Write("\nPress ENTER to Quit..");
Console.ReadLine();
} }
class MyArea{
public double RectArea(){
double Length, Breadth, RectangleArea;
Console.Write("Enter the Length of Rectangle:");
Length = double.Parse(Console.ReadLine());
Console.Write("Enter the Breadth of Rectangle:");
Breadth = double.Parse(Console.ReadLine());
RectangleArea = Length * Breadth;
Console.WriteLine("The Area of Rectangle is:" + RectangleArea);
return (RectangleArea);
} } }
10/7/2022 Dr. Ch. Ram Mohan Reddy 63
Describing Access Modifiers
• Access modifiers help to avoid jumbling of data and methods with the existing code
as well as protect an object of a class from outside interference.
• These modifiers do this by defining a certain scope to access data and methods in a
restricted manner.
• Declare a class and each of its methods with an access modifier. Each methods,
however, can contain only one modifier.
➢ Public modifier - Allows public access to members both inside and outside a
class with out any restrictions.
➢ Internal modifier - Allows internal access to members. Only the current
assembly can access these members. If a member of the internal accessibility
level is accessed outside the assembly in which it has been defined, an error is
generated.
➢ Protected modifier- Allows protected access to members. You can access
protected members from either the class in which they are declared or a class
derived from the class in which they are declared.
➢ Private modifier- Allows private access to members. Private members have the
least access permission level; you can either access them within the body of the
class or in the structure in which they are declared.
➢ Protected internal modifier - Allows access to the members of the current
assembly, the containing class, and the class derived from the containing class.

10/7/2022 Dr. Ch. Ram Mohan Reddy 64


Constructors
• It has the same name as its containing class
• It has no return type
• It is automatically called when a new instance or object of a class is created, hence
why it’s called a constructor.
• The constructor contains initialization code for each object, like assigning default
values to the fields.
public class MyClass {
public MyClass() {
}
// rest of class definition
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 65


//Constructors
using System;
class Person {
// field
private string name;
// constructor
public Person() {
name = "unknown";
Console.WriteLine("Constructor called...");
}
// property
public string Name {
get { return name; }
set { name = value; }
}
}
class Test {
public static void Main() {
Person thePerson = new Person();
Console.WriteLine("The name of person in object thePerson is " + thePerson.Name);
thePerson.Name = "Faraz";
Console.WriteLine("The name of person in object thePerson is " + thePerson.Name);
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 66


Destructors
• Destructors are just the opposite of constructors. These are methods with the following
properties
• It has the same name as the containing class but prefixes it with the ~ (tilde) sign. It is
called automatically when the object is about to be destructed (when garbage collector
is about to destroy your object).
• It has no return type.

class Person{
// constructor
public Person(){
}
// destructor
~Person(){
// put resource freeing code here.
}
}
• The C# compiler internally converts the destructor to the Finalize() method.

10/7/2022 Dr. Ch. Ram Mohan Reddy 67


Static Constructors
➢ It is also possible to write a static no-parameter constructor for a class. Such a
constructor will be executed only once, as opposed to the constructors written so
far, which are instance constructors, and are executed whenever an object of that
class is created.
Class MyClass {
static MyClass() {
// initialization code
}
// rest of class definition
}
➢ One reason for writing a static constructor is if your class has some static fields or
properties that need to be initialized from an external source before the class is
first used.
➢ Note that it is possible to have a static constructor and a zero-parameter instance
constructor defined in the same class. Although the parameter lists are identical,
there is no conflict, because the static constructor is executed when the class is
loaded, but the instance constructor is executed whenever an instance is created -
so there won’t be any confusion about which constructor gets executed when.
10/7/2022 Dr. Ch. Ram Mohan Reddy 68
// Use a Static Constructor
using System;
class cons {
public static int alpha;
public int beta;
// A static constructor
static cons() {
alpha = 99;
Console.WriteLine ("Inside Static Constructor");
}
// An instance constructor
public cons() {
beta = 100;
Console.WriteLine ("Inside instance constructor.");
}
}
class consDemo {
static void Main() {
cons ob = new cons();
Console.WriteLine ("Cons.alpha:" +cons.alpha);
Console.WriteLine ("ob.beta: "+ob.beta);
}
}
10/7/2022 Dr. Ch. Ram Mohan Reddy 69
Declaring static variable and a static method:-
• A static method does not have a this reference. This is because a static methods does
not execute relative to any object.
• A static method can directly call only static methods of its class. It cannot directly call
an instance method of its class. The reason is that instance methods operate on
specific objects, but a static method is not called on an object. Thus, on what object
would the static method operate?
• A static method can directly access only other static data defined by its class. It
cannot operate on an instance variable of its class because there is no object to
operate on.
// use static
using System;
class staticDemo {
// A Static Variable.
public static int val = 100;
// A static Method
public static int valDiv2() {
return val / 2;
} }
class sDemo{
static void Main() {
Console.WriteLine("Initial value of staticDemo.val is " + staticDemo.val);
staticDemo.val = 8;
Console.WriteLine("StaticDemo.val is " + staticDemo.val);
Console.WriteLine("StaticDemo.valDiv2 is " + staticDemo.valDiv2());
} }
10/7/2022 Dr. Ch. Ram Mohan Reddy 70
Static Class:-
• A class can be declared static, indicating that it contains only static members. It is not
possible to create instances of a static class using the new keyword. Static classes are
loaded automatically by the .NET Framework common language runtime (CLR) when
the program or namespace containing the class is loaded.
• Use a static class to contain methods that are not associated with a particular object.
For example, it is a common requirement to create a set of methods that do not act
on instance data and are not associated to a specific object in your code. You could
use a static class to hold those methods.
The main features of a static class are:
• They only contain static members.
• They cannot be instantiated.
• They are sealed.
• They cannot contain Instance Constructors.
• Creating a static class is therefore much the same as creating a class that contains
only static members and a private constructor. A private constructor prevents the
class from being instantiated.
• The advantage of using a static class is that the compiler can check to make sure that
no instance members are accidentally added. The compiler will guarantee that
instances of this class cannot be created.
• Static classes are sealed and therefore cannot be inherited. Static classes cannot
contain a constructor, although it is still possible to declare a static constructor to
assign initial values or set up some static state.
10/7/2022 Dr. Ch. Ram Mohan Reddy 71
Declaration:
• A static class is created by using keyword 'Static' as shown here:
Static class Classname {
//C#
}
• One thing that is notable-within static class, all members must be explicitly specified
as static, static class does not automatically make its members static.
• Static class can contain a collection of static methods.
Example: Example-2
using System; using System;
static class Shape { namespace ConsoleApplication12{
public static double GetArea(double Width, double height) { static class classA {
return Width * height; public static void dowork() {
} Console.WriteLine("Class A Called");
}
}
}
class Rectangle { class Program {
private void GetRectangleArea() { static void Main(string[] args){
Double Area; classA.dowork();
Area = Shape.GetArea(10, 5); Console.Read();
} }
} }
}
• Shape is static class, it contain static function GetArea.Rectangle is other class and with in
GetArea function can be access without creating instance of Class Shape.
• Although a static class cannot have an instance constructor, it can have a static constructor.
10/7/2022 Dr. Ch. Ram Mohan Reddy 72
An example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and vice versa:

Using system;
public static class TemperatureConverter {
public static double CelsiusToFahrenheit(string temperatureCelsius) {
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit) {
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
} }
class TestTemperatureConverter {
static void Main() {
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection) {
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
} } }
10/7/2022 Dr. Ch. Ram Mohan Reddy 73
Properties
➢ The properties are used to access the private fields outside the
class
➢ Property is a method or pair of methods that are dressed to look
like a field as far as any client code is concerned
To define a property in C#, you use the following syntax:
public string SomeProperty {
get {
return "This is the property value.";
}
set {
// do whatever needs to be done to set the property.
}
}
➢ The get accessor takes no parameters and must return the same
type as the declared property. You should not specify any explicit
parameters for the set accessor either, but the compiler assumes
it takes one parameter, which is of the same type again, and
which is referred to as value.

10/7/2022 Dr. Ch. Ram Mohan Reddy 74


E.g.
private string foreName;
public string ForeName
{
get {
return foreName;
}
set {
foreName = value;
}
}

Note the naming convention used here


➢ You take advantage of C#’s case sensitivity by using the same
name, Pascal-cased for the public property and camel-cased for the
equivalent private field if there is one

10/7/2022 Dr. Ch. Ram Mohan Reddy 75


Read-Only and Write-Only Properties
➢ It is possible to create a read-only property by simply omitting the set accessor
from the property definition
public string ForeName
{
get {
return foreName;
}
}
➢ It is similarly possible to create a write-only property by omitting the get accessor
public string ForeName
{
set {
foreName = value;
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 76


//C#: Property //C# : static Property
using System; using System;
class MyClass class MyClass
{ {
private int x; private static int x;
public int X public static int X
{ {
get get
{ {
return x; return x;
} }
set set
{ {
x = value; x = value;
} }
} }
} }
class MyClient { class MyClient {
public static void Main() { public static void Main() {
MyClass mc = new MyClass(); MyClass.X = 10;
mc.X = 10; int xVal = MyClass.X;
int xVal = mc.X; Console.WriteLine(xVal);//Displays 10
Console.WriteLine(xVal);//Displays 10 }
} }
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 77


//C# : Property : Inheritance //C# : Property : Polymorphism
using System; using System;
class Base class Base {
{ public virtual int X {
public int X get {
{ Console.Write("Base GET");
get return 10;
{ }
Console.Write("Base GET"); set {
return 10; Console.Write("Base SET");
} }
set } }
{ class Derived : Base {
Console.Write("Base SET"); public override int X {
} get {
} } Console.Write("Derived GET");
class Derived : Base{ return 10;
} }
class MyClient set {
{ Console.Write("Derived SET");
public static void Main() }
{ } }
Derived d1 = new Derived(); class MyClient {
d1.X = 10; public static void Main() {
Console.WriteLine(d1.X);//Displays 'Base SET Base GET Base b1 = new Derived();
10' b1.X = 10;
} } Console.WriteLine(b1.X);//Displays 'Derived SET Derived
GET 10'
} }
10/7/2022 Dr. Ch. Ram Mohan Reddy 78
Anonymous types
• Anonymous types provide a way to encapsulate the read-only properties of an object
into a single object without having to first explicitly define a type.
• The compiler generates the type name as required but this type name is not available at the
source code level.
• The compiler derives the properties type to generate the type name.
• Anonymous types create unnamed structure types that can add to the collections and access
those structure types using the var keyword.
• Anonymous types are the class types that consist of one or more public read-only properties.
No other kinds of class members such as methods or events are allowed.
• Use the new keyword with an object initializer to create an anonymous type.
• Anonymous types are reference types that are derived directly form the object. Two or more
anonymous types having the same number and type of properties in the same order are
treated as the same type by the compiler.
using System;
namespace MyAnonymousType {
class Program {
static void Main(string[] args) {
var product = new { Name = "Key Board", Price = 650 };
Console.WriteLine("Product Details");
Console.WriteLine("Name:" + product.Name);
Console.WriteLine("Price: Rs." + product.Price);
Console.Write("Press ENTER to quit...");
Console.ReadLine();
}
10/7/2022
} Dr. Ch. Ram Mohan Reddy 80
}
Indexers in C# .NET

• C# introduces a new concept known as Indexers which are used for treating an object as an
array. The indexers are usually known as smart arrays in C#. They are not essential part of
object-oriented programming.
• An indexer, also called an indexed property, is a class property that allows you to access a
member variable of a class using the features of an array.
• Defining an indexer allows you to create classes that act like virtual arrays. Instances of that
class can be accessed using the [] array access operator.
Creating an Indexer
<modifier> <return type> this [argument list]
{
get {
// your get block code
}
set{
// your set block code
}
}
In the above code:
<modifier> can be private, public, protected or internal.
<return type> can be any valid C# types.
this this is a special keyword in C# to indicate the object of the current class.
[argument list] The formal-argument-list specifies the parameters of the indexer.
10/7/2022 Dr. Ch. Ram Mohan Reddy 81
Important points to remember on indexers:
• Indexers are always created with this keyword.
• Parameterized property are called indexer.
• Indexers are implemented through get and set accessors for the [ ] operator.
• ref and out parameter modifiers are not permitted in indexer.
• The formal parameter list of an indexer corresponds to that of a method and at least one
parameter should be specified.
• Indexer is an instance member so can't be static but property can be static.
• Indexers are used on group of elements.
• Indexer is identified by its signature where as a property is identified it's name.
• Indexers are accessed using indexes where as properties are accessed by names.
• Indexer can be overloaded.

Indexer are defined in pretty much same way as properties, with get and set functions. The
main difference is that the name of the indexer is the keyword this.

10/7/2022 Dr. Ch. Ram Mohan Reddy 82


//Following program demonstrate how to use IndexerClass Team = new IndexerClass();
//indexer. Team[0] = "Rocky";
using System; Team[1] = "Teena";
namespace Indexer_example1 Team[2] = "Ana";
{ Team[3] = "Victoria";
class Program { Team[4] = "Yani";
class IndexerClass { Team[5] = "Mary";
private string[] names = new string[10]; Team[6] = "Gomes";
public string this[int i] { Team[7] = "Arnold";
get { Team[8] = "Mike";
return names[i]; Team[9] = "Peter";
} for (int i = 0; i < 10; i++) {
set { Console.WriteLine(Team[i]);
names[i] = value; }
} Console.ReadKey();
} }
} }
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 83


Difference between Indexers and Properties

Indexers Properties
•Indexers are created with this •Properties don't require this
keyword. keyword.
•Indexers are identified by •Properties are identified by their
signature. names.
•Indexers are accessed using •Properties are accessed by their
indexes. names.
•Indexer are instance member, so •Properties can be static as well as
can't be static. instance members.
•A get accessor of an indexer has •A get accessor of a property has
the same formal parameter list as no parameters.
the indexer.
•A set accessor of an indexer has •A set accessor of a property
the same formal parameter list as contains the implicit value
the indexer, in addition to the parameter.
value parameter.
•Difference between Indexers and Properties
Indexers are commonly used for classes, which represents some data structure,
an array, list, map and so on.

10/7/2022 Dr. Ch. Ram Mohan Reddy 84


Structs
The difference between structure and classes is that a structure is created on a stack,
Whereas, a class is created on a heap.
I.e.., struct is a value type and a class is a reference type.
Syntax –
[attributes] [modifiers] struct identifier [; interfaces]{
body[;]
}
attribute – Holds additional declarative information, It is optional.
modifier – allows modifiers such as new, static virtual, abstract, and override to be used in a struct.
It allows access modifiers, such as public, internal, and private to be used in a struct.This is optional.
struct – refers to the keyword that is mandatory while creating a struct. An identifier that
represents the name of the struct must follow the struct keyword.
interface – contains the interface list, separated by commas, It is optional.
body – contains all the member declarations.
Note – the protected and protected internal access modifiers cannot be used in structs because
structs are implicitly sealed. These means that a struct cannot be a parent class of other classes.
Struct members are private by default.

Access modifiers for structs-


Public – Allows access of the type or members by any other code in the same assembly or another
assembly that references it.
Private- Allows access of the type or members by the code in the same struct.
Internal- Allows access of the type or members by any code in the same assembly, but not from
another assembly.
10/7/2022 Dr. Ch. Ram Mohan Reddy 85
Structures using C#
Just like classes structs can have
1. Private Fields
2. Public properties
3. Constructors
4. Methods

Classes Vs. Structs


• A struct is a value type where as a class is a reference type.
• All the differences that are applicable to value types and reference types are also
applicable to classes and structs.
• Structs are stored on stack, where as classes are stored on the heap.
• Value types hold their value in memory where they are declared, but reference types
hold a reference to an object in memory.
• Value types are destroyed immediately after the scope is lost, where as for reference
types only the reference variable is destroyed after the scope is lost. The object is
later destroyed by garbage collector.
• Structures can’t have destructors, but classes can have destructors.
• Structs can’t inherit form another class where as a class can,. Both structs and
classes can inherit from an interface.

Note:- A class or a struct cannot inherit from another struct. Struct are sealed types.

10/7/2022 Dr. Ch. Ram Mohan Reddy 86


using System;
namespace MyStruct{
public struct X{
public int x;
public int y;
public int z;
}
class Foo{
static void Main(string[] args){
X x;
x.x = 1;
x.y = 2;
x.z = 3;
Console.WriteLine("X = {0}, Y = {1}, Z = {2}", x.x, x.y, x.z);
X x1 = new X();
Console.WriteLine("X = {0}, Y = {1}, Z = {2}", x1.x, x1.y, x1.z);
Console.Write("\nPress Enter to quit...");
Console.ReadLine();
}
}
}

10/7/2022 Dr. Ch. Ram Mohan Reddy 87


Quick Revise
Q1. Default constructors are constructors that do not have any parameters. State if this
statement is true or
false.
Ans. True.
Q2. __________ members are associated with the class as a whole and not with a
particular object.
Ans. Static.
Q3. __________ enables you to specify the definition of a class, structure, or interface in
two or more
source files.
Ans. Partial class
Q4. Name the access modifiers available in C#.
Ans. The access modifiers available in C# are private, public, protected, internal, and
protected internal.
Q5. What are constructors? Can constructors of a class have a return type?
Ans. Constructors are special methods of a class that are automatically called when an
instance of the class is created. No, a constructor cannot have a return type.
Q6. State one significant difference between structures and classes in C#.
Ans. Structures are value types and are stored on the stack, while classes are reference types
and are stored on the heap.

10/7/2022 Dr. Ch. Ram Mohan Reddy 88


Quick Revise
Q7. Can a static class have an instance member?
Ans. No, a static class cannot have an instance member. Static classes can only have static
members.
Q8. What is the difference between constants and read-only fields?
Ans. Constants are associated with classes that are accessible at compile-time; this means
that the value of the variable that you define as constant is calculated at compile-time. On
the other hand, read-only fields are also associated with classes or instances of classes. Their
values can be set during class declaration.
Q9. What is the use of the copy constructor?
Ans. A copy constructor is used to create a copy of an existing object as new object. A copy
constructor takes the reference of the object to be copied as an argument and creates
identical copies of objects that have the same value for properties and members as the
source object.
Q10. What is the difference between a property and an indexer?
Ans. A property allows methods to be called as if they were public data members. The
properties can be accessed through a simple name. On the other hand, an indexer allows
elements of an internal collection or an object to be accessed by using an array notation on
the object itself. However, an indexer can be accessed through an index.

10/7/2022 Dr. Ch. Ram Mohan Reddy 89

You might also like