Unit-1 2
Unit-1 2
Unit-1 2
• 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.
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
• 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.
• 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.
.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
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
Lowest priority =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
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;
// 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();
}
}
}
• 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();
}
}
}
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.
nested loops You can use one or more loop inside any another while, for or
do..while loop.
• 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();
• 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.
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);
}
}
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.
} }
} }
class Person{
// constructor
public Person(){
}
// destructor
~Person(){
// put resource freeing code here.
}
}
• The C# compiler internally converts the destructor to the Finalize() method.
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.
• 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.
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.
Note:- A class or a struct cannot inherit from another struct. Struct are sealed types.