SlideShare uma empresa Scribd logo
1 de 86
Dot Net Technology
Example C# Program
Here is a program that multiplies 10 by 20 and prints the result,
200, to the screen.
The double forward slash indicates that the remainder of a line is a
comment.
using System; // Importing namespace
class Test // Class declaration
{
static void Main() // Method declaration
{
int x = 10 * 20; // Statement 1
Console.WriteLine (x); // Statement 2
} // End of method
} // End of class
At the heart of this program lie two statements:
int x = 10 * 20;
Console.WriteLine (x);
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.
Eg: int Age;
Here, Age is the name of variable. Hence it is an identifier.
Reserved keywords can not be used as identifiers unless @
is added as prefix. For example,
int break; // not allowed
int @break; // allowed (keyword with prefix @)
Keywords
Keywords are predefined sets of reserved words that have special
meaning in a program. The meaning of keywords can not be changed,
neither can they be directly used as identifiers in a program.
C# has a total of 79 keywords,
abstract as base bool
break byte case catch
char checkedclass const
continue decimal default delegate
do double else enum
event explicit extern false
finally fixed float for
foreach goto if implicit
in in (generic modifier) int interface
C# Comments
The C# comments are statements that are not executed by the
compiler. The comments in C# programming can be used to
provide explanation of the code, variable, method or class. By the
help of comments, you can hide the program code also.
There are two types of comments in C#.
Single Line comment // comment
Multi Line comment
/* multile
Line
*/
Type Safety
C# is primarily a type-safe language, meaning that instances of types can
interact only through protocols they define, thereby ensuring each
type’s internal consistency. For instance, C# prevents you from
interacting with a string type as though it were an integer type. More
specifically, C# supports static typing, meaning that the language
enforces type safety at compile time.
C# is also called a strongly typed language because its type rules are
strictly enforced (whether statically or at runtime). For instance, you
cannot call a function that’s designed to accept an integer with a
floating-point number, unless you first explicitly convert the floating
point number to an integer. This helps prevent mistakes.
Int a ;
Type Basics
C# is a strongly-typed language. It means we must declare the type of a
variable that indicates the kind of values it is going to store, such as
integer, float, decimal, text, etc. In our example, we used two literals of
type int with values 10 and 20. We also declared a variable of type int
and name was x:
static void Main()
{
int x = 10 * 20;
Console.WriteLine (x);
}
A variable denotes a storage location that can contain different values over
time. In contrast, a constant always represents the same value (more on
this later): const int y = 200;
All values in C# are instances of a type. The meaning of a value, and the
set of possible values a variable can have, is determined by its type.
Data Types and Variables
 Data Types are an integral part in any programming
language. They represent how to express numbers,
characters, strings, decimal point values, and so forth.
 Like any programming language, C# defines the data type
to represent a variable. CLR provide two categories of data
type Value Type and Reference Type. Both types are stored
in different places of memory; a value type stores its value
directly in stack and reference types store a reference to the
value in a managed heap.
Value Type:
Value based data types(Value Type) include all numerical
data types such as Integer, Float, Byte, and so forth.
Reference Type:
Reference based data types(Reference Type) include
Classes, Interfaces, Delegates etc. If the value of one
variable gets changed, the value of the other variable also
reflects the same value.
Unlike value types, a reference type doesn't store its value directly.
Instead, it stores the address where the value is being stored. In other
words, a reference type contains a pointer to another memory location
that holds the data.
TestClass obj1, obj2;
obj1 = new TestClass();
obj2 = obj1;
Boxing and Unboxing
The conversion of a value type into a reference type is termed
as boxing; the conversion of a reference type into a value
type is termed as unboxing.
int sampleNumber = 5; //assignment statement
Object ob = sampleNumber; //boxing
int sampleNumber = 5; //assignment statement
Object ob1 = sampleNumber; //boxing
int num = (int)ob1; //unboxing
string value = (string)ob1;//unboxing
Jagged Array
Jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.
Declaration of Jagged array
Let's see an example to declare jagged array that has two elements.
int[][] arr = new int[2][];
Initialization of Jagged array
Let's see an example to initialize jagged array. The size of elements can be
different.
arr[0] = new int[4];
arr[1] = new int[6];
Initialization
Initialization and filling elements in Jagged array
Let's see an example to initialize and fill elements in jagged array.
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Here, size of elements in jagged array is optional. So, you can write above
code as given below:
arr[0] = new int[] { 11, 21, 56, 78 };
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
Example
public static void Main()
{
int[][] arr = new int[2][];// Declare the array
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
}
Class
Object Oriented programming organizes code by creating
types in the form of classes. These classes contain the code
that represents a specific entity. Everything in C# is
associated with classes and objects, along with its attributes
and methods.
class MyClass
{
public MyMthod()
{
}
}
Class example
public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance { get; }
public void MakeDeposit(decimal amount, DateTime date, string note)
{
}
public void MakeWithdrawal(decimal amount, DateTime date, string note)
{
}
}
Constructor
Constructor is a special method of the class that will invoke
automatically whenever an instance of class is created.
public class Employee
{
// Constructor
public Employee()
{
// Code
}
}
Some of the key points regarding constructor are
 A class can have any number of constructors.
 A constructor doesn't have any return type, not even void.
 A static constructor can not be a parametrized constructor.
 Within a class, you can create one static constructor only.
different type of constructors
C# Constructor Types
 Default Constructor
 Parameterized Constructor
 Copy Constructor
 Static Constructor
 Private Constructor
Default Constructor
class ClassName
{
public string name, location;
// Default Constructor
public ClassName()
{
name = "xyz";
location = "kathmandu"
}
}
Parameterized Constructor
class ClassName
{
public int a, b;
public ClassName(int x, int y) // decalaring
Paremetrized Constructor with ing x,y parameter
{
a = x;
b = y;
}
}
Destructors
Destructors are methods inside the class used to
destroy instances of that class when they are no
longer needed. The Destructor is called implicitly
by the .NET Framework’s Garbage collector and
therefore programmer has no control as when to
invoke the destructor. An instance variable or an
object is eligible for destruction when it is no
longer reachable.
example
class ClassName
{
ClassName()
{
}
// Destructor
~ClassName()
{
//code
}
}
Method/function
Method is a separate code block, and that contains a series of statements to
perform particular operations. Methods must be declared either in class or
struct by specifying the required parameters.
Generally, methods are useful to improve code reusability by reducing code
duplication. If we have the same functionality to perform in multiple places,
then we can create one method with the required functionality and use it
wherever it is required in the application.
example
<Access_Specifier> <Return_Type> Method_Name()
{
// Statements to Execute
}
public int Add(int a, int b) {
return a + b;
}
Access_Specifier - It is used to define an access level, either public or private, etc., to allow other
classes to access the method. If we didn’t mention any access modifier, then by default, it is
private.
Return_Type - It is used to specify the type of value the method can return. If the method is not
returning any value, then we need to mention void as the return type.
Method_Name - It must be a unique name to identify the method in a class.
Parameters - The method parameters are useful to send or receive data from a method, and these
method parameters are enclosed within parentheses and are separated by commas. If no
parameters are required for a method, we need to define a method with empty parentheses.
Example
static void PrintMethod()
{
Console.WriteLine(“Hello There!");
}
static void Main(string[] args)
{
PrintMethod();
}
Method overloading
Method Overloading is the common way of implementing polymorphism.
A method with the same name but the different signature is called method
overloading.
public int Add(int valueOne, int valueTwo)
{
return valueOne + valueTwo;
}
public int Add(int valueOne, int valueTwo, int valueThree)
{
return valueOne + valueTwo + valueThree;
}
Namespaces
Namespaces are used in C# to organize and provide a level of
separation of codes. They can be considered as a
container which consists of other namespaces, classes, etc.
A namespace can have following types as its members:
Namespaces (Nested Namespace)
Classes
Interfaces
Structures
Delegates
Defining Namespace in C#
We can define a namespace in C# using the namespace keyword as:
namespace Namespace-Name
{
//Body of namespace
}
Accessing namespace
Namespace-Name.item_name;
For example:
namespace MyNamespace
{
class MyClass
{
public void MyMethod()
{
System.Console.WriteLine("Creating my namespace");
}
}
}
Inheritance
Inheritance is a concept in which you define parent classes and child
classes. The child classes inherit methods and properties of the parent
class.
The original class is known as the base class and the class which inherits
the functionality of the base class is the derived class. Inheritance
provides code reusability and implementation speedup.
Single Level Inheritence
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
Multi level inheritence
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark() { Console.WriteLine("Barking..."); }
}
public class BabyDog : Dog
{
public void weep() { Console.WriteLine("Weeping..."); }
}
Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one subclass. For
example, class A serves as a base class for the derived
class B, C, and D.
Note: C# does not support multiple inheritance with classes.
In C#, we can achieve multiple inheritance only through
Interfaces.
Hierarchical Example
class A {
public void display() {
Console.WriteLine("A");
}
}
class B: A{
public void displayB() {
Console.WriteLine("B");
}
}
class C : A {
public void displayC() {
Console.WriteLine("C");
}
}
Interface
Like a class, Interface can have methods, properties, events, and
indexers as its members. But interfaces will contain only the
declaration of the members. The implementation of the interface’s
members will be given by class who implements the interface
implicitly or explicitly.
 Interfaces specify what a class must do and not how.
 Interfaces can't have private members.
 By default all the members of Interface are public and abstract.
 The interface will always defined with the help of keyword 'interface'.
 Interface cannot contain fields because they represent a particular
implementation of data.
 Multiple inheritance is possible with the help of Interfaces but
not with classes.
To declare an interface, use interface keyword. It is used to
provide total abstraction. That means all the members in the
interface are declared with the empty body and are public and
abstract by default. A class that implements interface must
implement all the methods declared in the interface.
Syntax for Interface Declaration:
interface interface_name
{
// declare methods
// declare properties
}
Syntax for Implementing Interface:
class class_name : interface_name
An interface contains definitions for a group of related functionalities
that a non-abstract class or a struct must implement. An interface may
define static methods, which must have an implementation. Beginning
with C# 8.0, an interface may define a default implementation for
members. An interface may not declare instance data such as fields,
auto-implemented properties, or property-like events.
Example
interface Vehicle {
// all are the abstract methods.
void speedUp(int a);
void applyBrake(int a);
}
// class implements interface
class Bicycle : Vehicle {
Advantage of Interface:
It is used to achieve loose coupling.
It is used to achieve total abstraction.
To achieve component-based programming
To achieve multiple inheritance and abstraction.
Interfaces add a plug and play like architecture into applications.
Abstract Class
An abstract class is a special type of class that cannot be
instantiated. It is marked by the keyword abstract. An abstract class
contains zero or more abstract methods in it. Abstract class acts as a
base class and is designed to be inherited by subclasses that either
implement or either override its method.
Example:
public abstract class Shape
{
public abstract void draw();
}
Abastract class example
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
Abstraction
Abstraction in C# is the process to hide the internal details and
showing only the functionality. The abstract modifier indicates the
incomplete implementation. The keyword abstract is used before the
class or method to declare the class or method as abstract .
Abstract Method:
An Abstract method is a method without a body. The implementation
of an abstract method is done by a derived class. When the derived
class inherits the abstract method from the abstract class.
public abstract void MethodName();
Method Overriding
If derived class defines same method as defined in its base class, it is known as
method overriding in C#. It is used to achieve runtime polymorphism. It enables
you to provide specific implementation of the method which is already provided by
its base class.
class Base
{
public virtual void Greetings()
{
Console.WriteLine("Base Class Saying Hello !");
}
}
class Sub : Base
{
public override void Greetings()
{
base.Greetings();
Console.WriteLine("Sub Class Saying Hello !");
}
}
The virtual and override Keywords
Polymorphism provides a way for a derived class to define its own version
of a method defined by its base class, using the override keyword in
C#. The process of re-implementing the base class non-static method
in the derived class with the same prototype (same signature defined in
the base class) is called Method Overriding. If we want to define a
method in a base class that may be (but does not have to be)
overridden by a derived class, we must mark the method with the
virtual keyword. The virtual keyword is used to modify a method,
property, indexer, or event declared in the base class and allow it to be
overridden in the derived class.
When a derived class needs to change the implementation details of a
virtual method, it does so by using the override keyword.
Virtual Keyword
It tells the compiler that this method can be overridden by derived
classes.
public virtual int myMethod()
{
}
Override Keyword
In the subclass, it tells the compiler that this method is overriding the
same named method in the base class.
public override int myMethod()
{
}
base keyword
The base keyword is used to access members and functionalities of the base class from
within a derived class: It serves two essential purposes.
 Accessing an overridden function member from the subclass.
 Calling a base-class constructor.
public class Animal
{
public virtual void Eat() {
Console.WriteLine(“Animal: Eat()");
}
}
public class Cat : Animal
{
public override void Eat()
{
base.Eat();
Console.WriteLine("Cat: Eat()");
}
}
“this” Keyword
“this” keyword represents the pointer of a class or a stuct.
The this pointer represents the current instance of a class or stuct.
The “this” keyword in C# is used to refer to the current instance of the
class. It is also used to differentiate between the method parameters
and class fields if they both have the same name.
Another usage of “this” keyword is to call another constructor from a
constructor in the same class.
Here, for an example, we are showing a record of Students i.e: id, Name,
Age, and Subject. To refer to the fields of the current class, we have
used the “this” keyword in C# −
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
class Student {
public int id, age;
public String name, subject;
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
public void showInfo() {
Console.WriteLine(id + " " + name+" "+age+ " "+subject);
}
}
Access Modifiers
Access modifiers are the keywords that are used to specify accessibility or scope of
variables and functions in the C# Program. To promote encapsulation, a type or type
member can limit its accessibility to other types and other assemblies by adding one of
six access modifiers to the declaration:
private
Member is accessible inside the type only. This is the default.
internal
Member is accessible inside the type and any type in the same assembly.
protected
Member is accessible inside the type and any type that inherits from the type.
public
Member is accessible everywhere.
internal protected
Member is accessible inside the type, any type in the same assembly, and any type that
inherits from the type. Equivalent to a fictional access modifier named
internal_or_protected.
private protected
Member is accessible inside the type, or any type that inherits from the type and is in the
same assembly. Equivalent to a fictional access modifier named internal_and_protected.
This combination is only available with C# 7.2 or later.
Enums (Enumeration Types)
An enum is a special "class" that represents a group of constants or
An enumeration type (or enum type) is a value type defined by a set of
named constants of the underlying integral numeric type. To define
an enumeration type, use the enum keyword and specify the names of
enum members:
enum Season
{
Spring,
Summer,
Autumn,
Winter
}
By default, the associated constant values of enum members are
of type int; they start with zero and increase by one following the
definition text order. You can explicitly specify any other integral
numeric type as an underlying type of an enumeration type. You
can also explicitly specify the associated constant values, as the
following example shows:
enum ScreenCode : ushort
{
Top = 1,
Right = 2,
Bottom = 3,
Left = 4
}
Conversions
For any enumeration type, there exist explicit conversions between the enumeration type and its
underlying integral type. If you cast an enum value to its underlying type, the result is the associated
integral value of an enum member.
public enum Season
{
Spring,
Summer,
Autumn,
Winter
}
public class EnumConversionExample
{
public static void Main()
{
Season a = Season.Autumn;
Console.WriteLine($"Integral value of {a} is {(int)a}"); // output: Integral value of Autumn is 2
var b = (Season)1;
Console.WriteLine(b); // output: Summer
var c = (Season)4;
Console.WriteLine(c); // output: 4
}
}
Structs
A struct is a user-defined type that represents data structures. It is
similar to a class, with the following key differences:
 A struct is a value type, where a class is a reference type.
 A struct does not support inheritance
A struct can have all of the members that a class can, except a
parameterless constructor, field initializers, a finalizer, virtual or
protected members. In C#, structures are defined using the struct
keyword. The default modifier is internal for the struct and its
members.
The general structure for defining a struct is as shown below:
struct StructureName
{
//data members
}
A struct object can be created with or without the new operator, same as primitive
type variables.
struct Point
{
public int X;
public int Y;
}
Point pt;
pt.X = 100;
pt.Y = 50;
A struct can contain properties, auto-implemented properties, methods, etc., same as
classes.
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public void Increment()
{
X++; Y++;
}
}
A struct cannot contain a parameterless constructor. It can only contain
parameterized constructors or a static constructor. When you define a
struct constructor, you must explicitly assign every field.
struct Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x; this.y = y;
}
}
Point p1 = new Point();
Point p2 = new Point(2, 4);
The readonly modifier on a struct definition declares that the struct is
immutable. The Every instance field of the struct must be marked
readonly, as shown in the following example:
readonly struct Point
{
public readonly int X, Y; // X and Y must be readonly
}
It guarantees that no member of the struct can manipulate its content as
it ensures every field is marked as readonly. Adding a field not marked
as readonly will generate the following compiler error:
CS8340: "Instance fields of readonly structs must be readonly."
This guarantee is important because it allows the compiler to avoid
defensive copies of struct values.
Unlike reference types, whose instances always live on the heap, value
types live in-place wherever the variable was declared. If a value type
appears as a parameter or local variable, it will reside on the stack:
struct Point { public int X, Y; }
void SomeMethod()
{
Point pt; // pt will reside on the stack
}
Generics
Generic means the general form, not specific. In C#, generic means not
specific to a particular data type.
C# allows you to define generic classes, interfaces, abstract classes, fields,
methods, static methods, properties, events, delegates, and operators
using the type parameter and without the specific data type. A type
parameter is a placeholder for a particular type specified when creating
an instance of the generic type.
A generic type is declared by specifying a type parameter in an angle
brackets after a type name, e.g. TypeName<T> where T is a type
parameter.
Generic Class
Generic classes are defined using a type parameter in an angle brackets after
the class name. The following defines a generic class.
Example: Define Generic Class
class DataStore<T>
{
public T Data { get; set; }
}
Above, the DataStore is a generic class. T is called type parameter, which can
be used as a type of fields, properties, method parameters, return types,
and delegates in the DataStore class. For example, Data is generic property
because we have used a type parameter T as its type instead of the specific
data type.
Instantiating Generic Class
You can create an instance of generic classes by specifying an actual type
in angle brackets. The following creates an instance of the generic class
DataStore.
DataStore<string> store = new DataStore<string>();//generic
DataStore store = new DataStore();//regular
Above, we specified the string type in the angle brackets while creating an
instance. So, T will be replaced with a string type wherever T is used in
the entire class at compile-time. Therefore, the type of Data property
would be a string.
It is not required to use T as a type parameter. You can
give any name to a type parameter. Generally, T is used
when there is only one type parameter. It is
recommended to use a more readable type parameter
name as per requirement like TSession, TKey, TValue
You can also define multiple type parameters separated by a comma.
Example: Generic Class with Multiple Type Parameters
class KeyValuePair<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
}
Generic Fields
A generic class can include generic fields. However, it cannot be
initialized.
Example: Generic Field
class DataStore<T>
{
public T data;
}
The following declares a generic array.
Example: Generic Array
class DataStore<T>
{
public T[] data = new T[10];
}
Generic Methods
A method declared with the type parameters for its return type or parameters is called a
generic method.
class DataStore<T>
{
private T[] _data = new T[10];
public void AddOrUpdate(int index, T item)
{
if(index >= 0 && index < 10)
_data[index] = item;
}
public T GetData(int index)
{
if(index >= 0 && index < 10)
return _data[index];
else
return default(T);
}
}
Properties
Properties are named members of classes, structures, and interfaces. Member
variables or methods in a class or structures are called Fields. Properties are an
extension of fields and are accessed using the same syntax. They use accessors
through which the values of the private fields can be read, written or
manipulated.
Properties do not name the storage locations. Instead, they have accessors that
read, write, or compute their values.
For example, let us have a class named Student, with private fields for name,
address and phone. We cannot directly access these fields from outside the
class scope, but we can have properties for accessing these private fields
Before going on properties lets have a look at why the concept of properties came
into C#? The is because of two reasons:
 If the members of a class are private then how another class in C# will be able
to read, write, or compute the value that field.
 If the members of the class are public then another class may misuse that
member.
Properties
public class Student
{
private string name; //field
public string Name //property
{
get
{
return name;
}
set
{
name = value;
}
}
}
Properties are the special type of class members that provides a flexible
mechanism to read, write, or compute the value of a private field. Properties can
be used as if they are public data members, but they are actually special methods
called accessors.
Accessors: The block of "set" and "get" is known as "Accessors". It is very essential to restrict
the accessibility of property. There are two type of accessors i.e. get accessors and set
accessors. There are different types of properties based on the "get" and set accessors:
Read and Write Properties: When property contains both get and set methods.
Read-Only Properties: When property contains only get method.
Write Only Properties: When property contains only set method.
Auto Implemented Properties: When there is no additional logic in the property accessors
and it introduce in C# 3.0.
The syntax for Defining Properties:
<access_modifier> <return_type> <property_name>
{
get { // body }
set { // body }
}
Properties
Indexers
An indexer is a special type of property that allows a class or a structure to be accessed like
an array for its internal collection. C# allows us to define custom indexers, generic
indexers, and also overload indexers.
An indexer can be defined the same way as property with this keyword and square brackets
[].
Syntax
<return type> this[<parameter type> index]
{
get{
// return the value from the specified index of an internal collection
}
set{
// set values at the specified index in an internal collection
}
}
class IndexerExample
{
Private string[] valueArray = new string[3];
// Indexer declaration, this - is the keyword having a parameters list
public string this[int index]
{
get
{
return valueArray[index];
}
set
{
valueArray[index] = value;
}
}
}
public static void Main() {
IndexerExample indexerExample = new IndexerExample();
indexerExample[0] = "first";
indexerExample[1] = "second";
indexerExample[2] = "third";
Console.Write("Printing values stored in objects used as arraysn");
Console.WriteLine("First value = {0}", ic[0]);
Console.WriteLine("Second value = {0}", ic[1]);
Console.WriteLine("Third value = {0}", ic[2]);
}
LINQ
LINQ is 'Language Integrated Query,' and introduced in .NET Framework 3.5 to
query the data from different sources of data such as collections, generics, XML
documents, ADO.NET Datasets, SQL, Web Services, etc. in C# and VB.NET.
LINQ provides the rich, standardized query syntax in a .NET programming
language such as C# and VB.NET, which allows the developers to interact with
any data sources.
In C# or VB.NET, LINQ functionality can be achieved by importing the
System.Linq namespace in our application. Generally, the LINQ contains a set
of extension methods which allows us to query the source of data object
directly in our code based on the requirement.
Advantages of LINQ
We do not need to learn new query language syntaxes for different sources of data
because it provides the standard query syntax for the various data sources.
In LINQ, we have to write the Less code in comparison to the traditional
approach. With the use of LINQ, we can minimize the code.
LINQ provides the compile-time error checking as well as intelligence support in Visual
Studio. This powerful feature helps us to avoid run-time errors.
LINQ provides a lot of built-in methods that we can be used to perform the different
operations such as filtering, ordering, grouping, etc. which makes our work easy.
The query of LINQ can be reused.
Disadvantages of LINQ
With the use of LINQ, it's very difficult to write a complex query like SQL.
It was written in the code, and we cannot make use of the Cache Execution plan, which is the SQL feature as
we do in the stored procedure.
If the query is not written correctly, then the performance will be degraded.
If we make some changes to our queries, then we need to recompile the application and need to redeploy the
dll to the server.
A query is nothing but a set of instructions. Queries are applied to the data source
(i.e., in-memory object, SQL, XML, etc.) to perform the operations (i.e., CRUD
operations) and show the shape of the output from that Query. This means
that the Query is not responsible for what will be the output; instead, it is
responsible for the shape of the output.
Each Query is a combination of three things; they are:
Initialization(to work with a particular data source)
Condition(where, filter, sorting condition)
Selection (single selection, group selection or joining)
IList<Student> studentList = new List<Student>()
{
new Student() { StudentID = 1, StudentName = "John", Age = 18, StandardID = 1
} ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 21, StandardID =
1 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18, StandardID = 2
} ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20, StandardID =
2 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 }
};
var studentNames = studentList.Where(s => s.Age > 18)
.Select(s => s)
.Where(st => st.StandardID > 0)
.Select(s => s.StudentName);
using System.linq;
int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
IEnumerable<int> result =
from numbers in Num
where numbers > 5
select numbers;
//equivalent SQL
Select * from Num where number > 5;
ADO.NET
ADO.NET is a part of .NET framework architecture. It is
a model used by the applications to communicate with
a database for manipulating data
ADO.NET is a database access Technology
using System.Data.SqlClient;
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.SQLEXPRESS; Initial Catalog=School; integrated
security=True");
// Writing insert query
string query = "insert into Users(Name, Age, Email, Password)" +
"values('" + name.Text + "', '" + Int32.Parse(age.Text) + "', '" + email.Text + "','" + password.Text
+ "')";
SqlCommand sc = new SqlCommand(query, con);
// Opening connection
con.Open();
// Executing query
int status = sc.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("OOPs, something went wrong." + ex);
}
// Closing the connection
finally
{
con.Close();
}
SqlConnection connection = null;
try
{
connection = new SqlConnection("Data Source=.SQLEXPRESS; Initial Catalog=School; Integrated
Security=True"); //db server details
connection.Open();
//actual connection is opened here
SqlCommand command = new SqlCommand("SELECT * from Students", connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Response.Write((reader.GetInt32(0) +
reader.GetString(1)));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
connection = new SqlConnection("Data Source=.SQLEXPRESS; Initial
Catalog=School; Integrated Security=True"); //db server details
connection.Open();
//actual connection is opened here
cmd = new SqlCommand("delete from Students where ID = " + txtrn.Text
+ " ", conn);
cmd.ExecuteNonQuery();
Update
conn = new SqlConnection(connstring);
conn.Open();
comm = new SqlCommand("update student_detail set s_name= '"+txtname.Text+"',
age= "+txtage.Text+" , course=' "+txtcourse.Text+"' where roll_no =
"+txtrn.Text+" ", conn);
try
{
comm.ExecuteNonQuery();
MessageBox.Show("Updated..");
}
catch (Exception)
{
MessageBox.Show(" Not Updated");
}
finally
{
conn.Close();
}

Mais conteúdo relacionado

Semelhante a Notes(1).pptx

Semelhante a Notes(1).pptx (20)

C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
C programming notes
C programming notesC programming notes
C programming notes
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdf
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
c# at f#
c# at f#c# at f#
c# at f#
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
C#ppt
C#pptC#ppt
C#ppt
 
Chapter3: fundamental programming
Chapter3: fundamental programmingChapter3: fundamental programming
Chapter3: fundamental programming
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Visual c sharp
Visual c sharpVisual c sharp
Visual c sharp
 

Último

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Notes(1).pptx

  • 2. Example C# Program Here is a program that multiplies 10 by 20 and prints the result, 200, to the screen. The double forward slash indicates that the remainder of a line is a comment. using System; // Importing namespace class Test // Class declaration { static void Main() // Method declaration { int x = 10 * 20; // Statement 1 Console.WriteLine (x); // Statement 2 } // End of method } // End of class At the heart of this program lie two statements: int x = 10 * 20; Console.WriteLine (x);
  • 3. 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.
  • 4. Eg: int Age; Here, Age is the name of variable. Hence it is an identifier. Reserved keywords can not be used as identifiers unless @ is added as prefix. For example, int break; // not allowed int @break; // allowed (keyword with prefix @)
  • 5. Keywords Keywords are predefined sets of reserved words that have special meaning in a program. The meaning of keywords can not be changed, neither can they be directly used as identifiers in a program. C# has a total of 79 keywords, abstract as base bool break byte case catch char checkedclass const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in in (generic modifier) int interface
  • 6. C# Comments The C# comments are statements that are not executed by the compiler. The comments in C# programming can be used to provide explanation of the code, variable, method or class. By the help of comments, you can hide the program code also. There are two types of comments in C#. Single Line comment // comment Multi Line comment /* multile Line */
  • 7. Type Safety C# is primarily a type-safe language, meaning that instances of types can interact only through protocols they define, thereby ensuring each type’s internal consistency. For instance, C# prevents you from interacting with a string type as though it were an integer type. More specifically, C# supports static typing, meaning that the language enforces type safety at compile time. C# is also called a strongly typed language because its type rules are strictly enforced (whether statically or at runtime). For instance, you cannot call a function that’s designed to accept an integer with a floating-point number, unless you first explicitly convert the floating point number to an integer. This helps prevent mistakes. Int a ;
  • 8. Type Basics C# is a strongly-typed language. It means we must declare the type of a variable that indicates the kind of values it is going to store, such as integer, float, decimal, text, etc. In our example, we used two literals of type int with values 10 and 20. We also declared a variable of type int and name was x: static void Main() { int x = 10 * 20; Console.WriteLine (x); } A variable denotes a storage location that can contain different values over time. In contrast, a constant always represents the same value (more on this later): const int y = 200; All values in C# are instances of a type. The meaning of a value, and the set of possible values a variable can have, is determined by its type.
  • 9. Data Types and Variables  Data Types are an integral part in any programming language. They represent how to express numbers, characters, strings, decimal point values, and so forth.  Like any programming language, C# defines the data type to represent a variable. CLR provide two categories of data type Value Type and Reference Type. Both types are stored in different places of memory; a value type stores its value directly in stack and reference types store a reference to the value in a managed heap.
  • 10. Value Type: Value based data types(Value Type) include all numerical data types such as Integer, Float, Byte, and so forth.
  • 11. Reference Type: Reference based data types(Reference Type) include Classes, Interfaces, Delegates etc. If the value of one variable gets changed, the value of the other variable also reflects the same value. Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data. TestClass obj1, obj2; obj1 = new TestClass(); obj2 = obj1;
  • 12. Boxing and Unboxing The conversion of a value type into a reference type is termed as boxing; the conversion of a reference type into a value type is termed as unboxing. int sampleNumber = 5; //assignment statement Object ob = sampleNumber; //boxing int sampleNumber = 5; //assignment statement Object ob1 = sampleNumber; //boxing int num = (int)ob1; //unboxing string value = (string)ob1;//unboxing
  • 13. Jagged Array Jagged array is also known as "array of arrays" because its elements are arrays. The element size of jagged array can be different.
  • 14. Declaration of Jagged array Let's see an example to declare jagged array that has two elements. int[][] arr = new int[2][]; Initialization of Jagged array Let's see an example to initialize jagged array. The size of elements can be different. arr[0] = new int[4]; arr[1] = new int[6];
  • 15. Initialization Initialization and filling elements in Jagged array Let's see an example to initialize and fill elements in jagged array. arr[0] = new int[4] { 11, 21, 56, 78 }; arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 }; Here, size of elements in jagged array is optional. So, you can write above code as given below: arr[0] = new int[] { 11, 21, 56, 78 }; arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
  • 16. Example public static void Main() { int[][] arr = new int[2][];// Declare the array arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array arr[1] = new int[] { 42, 61, 37, 41, 59, 63 }; // Traverse array elements for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr[i].Length; j++) { System.Console.Write(arr[i][j]+" "); } System.Console.WriteLine(); } }
  • 17. Class Object Oriented programming organizes code by creating types in the form of classes. These classes contain the code that represents a specific entity. Everything in C# is associated with classes and objects, along with its attributes and methods. class MyClass { public MyMthod() { } }
  • 18. Class example public class BankAccount { public string Number { get; } public string Owner { get; set; } public decimal Balance { get; } public void MakeDeposit(decimal amount, DateTime date, string note) { } public void MakeWithdrawal(decimal amount, DateTime date, string note) { } }
  • 19. Constructor Constructor is a special method of the class that will invoke automatically whenever an instance of class is created. public class Employee { // Constructor public Employee() { // Code } }
  • 20. Some of the key points regarding constructor are  A class can have any number of constructors.  A constructor doesn't have any return type, not even void.  A static constructor can not be a parametrized constructor.  Within a class, you can create one static constructor only.
  • 21. different type of constructors C# Constructor Types  Default Constructor  Parameterized Constructor  Copy Constructor  Static Constructor  Private Constructor
  • 22. Default Constructor class ClassName { public string name, location; // Default Constructor public ClassName() { name = "xyz"; location = "kathmandu" } }
  • 23. Parameterized Constructor class ClassName { public int a, b; public ClassName(int x, int y) // decalaring Paremetrized Constructor with ing x,y parameter { a = x; b = y; } }
  • 24. Destructors Destructors are methods inside the class used to destroy instances of that class when they are no longer needed. The Destructor is called implicitly by the .NET Framework’s Garbage collector and therefore programmer has no control as when to invoke the destructor. An instance variable or an object is eligible for destruction when it is no longer reachable.
  • 26. Method/function Method is a separate code block, and that contains a series of statements to perform particular operations. Methods must be declared either in class or struct by specifying the required parameters. Generally, methods are useful to improve code reusability by reducing code duplication. If we have the same functionality to perform in multiple places, then we can create one method with the required functionality and use it wherever it is required in the application.
  • 27. example <Access_Specifier> <Return_Type> Method_Name() { // Statements to Execute } public int Add(int a, int b) { return a + b; } Access_Specifier - It is used to define an access level, either public or private, etc., to allow other classes to access the method. If we didn’t mention any access modifier, then by default, it is private. Return_Type - It is used to specify the type of value the method can return. If the method is not returning any value, then we need to mention void as the return type. Method_Name - It must be a unique name to identify the method in a class. Parameters - The method parameters are useful to send or receive data from a method, and these method parameters are enclosed within parentheses and are separated by commas. If no parameters are required for a method, we need to define a method with empty parentheses.
  • 28. Example static void PrintMethod() { Console.WriteLine(“Hello There!"); } static void Main(string[] args) { PrintMethod(); }
  • 29. Method overloading Method Overloading is the common way of implementing polymorphism. A method with the same name but the different signature is called method overloading. public int Add(int valueOne, int valueTwo) { return valueOne + valueTwo; } public int Add(int valueOne, int valueTwo, int valueThree) { return valueOne + valueTwo + valueThree; }
  • 30. Namespaces Namespaces are used in C# to organize and provide a level of separation of codes. They can be considered as a container which consists of other namespaces, classes, etc. A namespace can have following types as its members: Namespaces (Nested Namespace) Classes Interfaces Structures Delegates
  • 31. Defining Namespace in C# We can define a namespace in C# using the namespace keyword as: namespace Namespace-Name { //Body of namespace } Accessing namespace Namespace-Name.item_name; For example: namespace MyNamespace { class MyClass { public void MyMethod() { System.Console.WriteLine("Creating my namespace"); } } }
  • 32. Inheritance Inheritance is a concept in which you define parent classes and child classes. The child classes inherit methods and properties of the parent class. The original class is known as the base class and the class which inherits the functionality of the base class is the derived class. Inheritance provides code reusability and implementation speedup.
  • 33. Single Level Inheritence public class Employee { public float salary = 40000; } public class Programmer: Employee { public float bonus = 10000; }
  • 34. Multi level inheritence public class Animal { public void eat() { Console.WriteLine("Eating..."); } } public class Dog: Animal { public void bark() { Console.WriteLine("Barking..."); } } public class BabyDog : Dog { public void weep() { Console.WriteLine("Weeping..."); } }
  • 35. Hierarchical Inheritance In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. For example, class A serves as a base class for the derived class B, C, and D. Note: C# does not support multiple inheritance with classes. In C#, we can achieve multiple inheritance only through Interfaces.
  • 36. Hierarchical Example class A { public void display() { Console.WriteLine("A"); } } class B: A{ public void displayB() { Console.WriteLine("B"); } } class C : A { public void displayC() { Console.WriteLine("C"); } }
  • 37. Interface Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface’s members will be given by class who implements the interface implicitly or explicitly.  Interfaces specify what a class must do and not how.  Interfaces can't have private members.  By default all the members of Interface are public and abstract.  The interface will always defined with the help of keyword 'interface'.  Interface cannot contain fields because they represent a particular implementation of data.  Multiple inheritance is possible with the help of Interfaces but not with classes.
  • 38. To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the members in the interface are declared with the empty body and are public and abstract by default. A class that implements interface must implement all the methods declared in the interface. Syntax for Interface Declaration: interface interface_name { // declare methods // declare properties } Syntax for Implementing Interface: class class_name : interface_name
  • 39. An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement. An interface may define static methods, which must have an implementation. Beginning with C# 8.0, an interface may define a default implementation for members. An interface may not declare instance data such as fields, auto-implemented properties, or property-like events. Example interface Vehicle { // all are the abstract methods. void speedUp(int a); void applyBrake(int a); } // class implements interface class Bicycle : Vehicle {
  • 40. Advantage of Interface: It is used to achieve loose coupling. It is used to achieve total abstraction. To achieve component-based programming To achieve multiple inheritance and abstraction. Interfaces add a plug and play like architecture into applications.
  • 41. Abstract Class An abstract class is a special type of class that cannot be instantiated. It is marked by the keyword abstract. An abstract class contains zero or more abstract methods in it. Abstract class acts as a base class and is designed to be inherited by subclasses that either implement or either override its method. Example: public abstract class Shape { public abstract void draw(); }
  • 42. Abastract class example public abstract class Shape { public abstract void draw(); } public class Rectangle : Shape { public override void draw() { Console.WriteLine("drawing rectangle..."); } } public class Circle : Shape { public override void draw() { Console.WriteLine("drawing circle..."); } }
  • 43.
  • 44. Abstraction Abstraction in C# is the process to hide the internal details and showing only the functionality. The abstract modifier indicates the incomplete implementation. The keyword abstract is used before the class or method to declare the class or method as abstract . Abstract Method: An Abstract method is a method without a body. The implementation of an abstract method is done by a derived class. When the derived class inherits the abstract method from the abstract class. public abstract void MethodName();
  • 45. Method Overriding If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already provided by its base class. class Base { public virtual void Greetings() { Console.WriteLine("Base Class Saying Hello !"); } } class Sub : Base { public override void Greetings() { base.Greetings(); Console.WriteLine("Sub Class Saying Hello !"); } }
  • 46. The virtual and override Keywords Polymorphism provides a way for a derived class to define its own version of a method defined by its base class, using the override keyword in C#. The process of re-implementing the base class non-static method in the derived class with the same prototype (same signature defined in the base class) is called Method Overriding. If we want to define a method in a base class that may be (but does not have to be) overridden by a derived class, we must mark the method with the virtual keyword. The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. When a derived class needs to change the implementation details of a virtual method, it does so by using the override keyword.
  • 47. Virtual Keyword It tells the compiler that this method can be overridden by derived classes. public virtual int myMethod() { } Override Keyword In the subclass, it tells the compiler that this method is overriding the same named method in the base class. public override int myMethod() { }
  • 48. base keyword The base keyword is used to access members and functionalities of the base class from within a derived class: It serves two essential purposes.  Accessing an overridden function member from the subclass.  Calling a base-class constructor. public class Animal { public virtual void Eat() { Console.WriteLine(“Animal: Eat()"); } } public class Cat : Animal { public override void Eat() { base.Eat(); Console.WriteLine("Cat: Eat()"); } }
  • 49. “this” Keyword “this” keyword represents the pointer of a class or a stuct. The this pointer represents the current instance of a class or stuct. The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name. Another usage of “this” keyword is to call another constructor from a constructor in the same class. Here, for an example, we are showing a record of Students i.e: id, Name, Age, and Subject. To refer to the fields of the current class, we have used the “this” keyword in C# − public Student(int id, String name, int age, String subject) { this.id = id; this.name = name; this.subject = subject; this.age = age; }
  • 50. class Student { public int id, age; public String name, subject; public Student(int id, String name, int age, String subject) { this.id = id; this.name = name; this.subject = subject; this.age = age; } public void showInfo() { Console.WriteLine(id + " " + name+" "+age+ " "+subject); } }
  • 51. Access Modifiers Access modifiers are the keywords that are used to specify accessibility or scope of variables and functions in the C# Program. To promote encapsulation, a type or type member can limit its accessibility to other types and other assemblies by adding one of six access modifiers to the declaration: private Member is accessible inside the type only. This is the default. internal Member is accessible inside the type and any type in the same assembly. protected Member is accessible inside the type and any type that inherits from the type. public Member is accessible everywhere. internal protected Member is accessible inside the type, any type in the same assembly, and any type that inherits from the type. Equivalent to a fictional access modifier named internal_or_protected. private protected Member is accessible inside the type, or any type that inherits from the type and is in the same assembly. Equivalent to a fictional access modifier named internal_and_protected. This combination is only available with C# 7.2 or later.
  • 52. Enums (Enumeration Types) An enum is a special "class" that represents a group of constants or An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: enum Season { Spring, Summer, Autumn, Winter }
  • 53. By default, the associated constant values of enum members are of type int; they start with zero and increase by one following the definition text order. You can explicitly specify any other integral numeric type as an underlying type of an enumeration type. You can also explicitly specify the associated constant values, as the following example shows: enum ScreenCode : ushort { Top = 1, Right = 2, Bottom = 3, Left = 4 }
  • 54. Conversions For any enumeration type, there exist explicit conversions between the enumeration type and its underlying integral type. If you cast an enum value to its underlying type, the result is the associated integral value of an enum member. public enum Season { Spring, Summer, Autumn, Winter } public class EnumConversionExample { public static void Main() { Season a = Season.Autumn; Console.WriteLine($"Integral value of {a} is {(int)a}"); // output: Integral value of Autumn is 2 var b = (Season)1; Console.WriteLine(b); // output: Summer var c = (Season)4; Console.WriteLine(c); // output: 4 } }
  • 55. Structs A struct is a user-defined type that represents data structures. It is similar to a class, with the following key differences:  A struct is a value type, where a class is a reference type.  A struct does not support inheritance A struct can have all of the members that a class can, except a parameterless constructor, field initializers, a finalizer, virtual or protected members. In C#, structures are defined using the struct keyword. The default modifier is internal for the struct and its members. The general structure for defining a struct is as shown below: struct StructureName { //data members }
  • 56. A struct object can be created with or without the new operator, same as primitive type variables. struct Point { public int X; public int Y; } Point pt; pt.X = 100; pt.Y = 50; A struct can contain properties, auto-implemented properties, methods, etc., same as classes. struct Point { public int X { get; set; } public int Y { get; set; } public void Increment() { X++; Y++; } }
  • 57. A struct cannot contain a parameterless constructor. It can only contain parameterized constructors or a static constructor. When you define a struct constructor, you must explicitly assign every field. struct Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } Point p1 = new Point(); Point p2 = new Point(2, 4);
  • 58. The readonly modifier on a struct definition declares that the struct is immutable. The Every instance field of the struct must be marked readonly, as shown in the following example: readonly struct Point { public readonly int X, Y; // X and Y must be readonly } It guarantees that no member of the struct can manipulate its content as it ensures every field is marked as readonly. Adding a field not marked as readonly will generate the following compiler error: CS8340: "Instance fields of readonly structs must be readonly." This guarantee is important because it allows the compiler to avoid defensive copies of struct values.
  • 59. Unlike reference types, whose instances always live on the heap, value types live in-place wherever the variable was declared. If a value type appears as a parameter or local variable, it will reside on the stack: struct Point { public int X, Y; } void SomeMethod() { Point pt; // pt will reside on the stack }
  • 60. Generics Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type. A type parameter is a placeholder for a particular type specified when creating an instance of the generic type. A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
  • 61. Generic Class Generic classes are defined using a type parameter in an angle brackets after the class name. The following defines a generic class. Example: Define Generic Class class DataStore<T> { public T Data { get; set; } } Above, the DataStore is a generic class. T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.
  • 62. Instantiating Generic Class You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore. DataStore<string> store = new DataStore<string>();//generic DataStore store = new DataStore();//regular Above, we specified the string type in the angle brackets while creating an instance. So, T will be replaced with a string type wherever T is used in the entire class at compile-time. Therefore, the type of Data property would be a string.
  • 63. It is not required to use T as a type parameter. You can give any name to a type parameter. Generally, T is used when there is only one type parameter. It is recommended to use a more readable type parameter name as per requirement like TSession, TKey, TValue
  • 64. You can also define multiple type parameters separated by a comma. Example: Generic Class with Multiple Type Parameters class KeyValuePair<K, V> { public K Key { get; set; } public V Value { get; set; } }
  • 65. Generic Fields A generic class can include generic fields. However, it cannot be initialized. Example: Generic Field class DataStore<T> { public T data; } The following declares a generic array. Example: Generic Array class DataStore<T> { public T[] data = new T[10]; }
  • 66. Generic Methods A method declared with the type parameters for its return type or parameters is called a generic method. class DataStore<T> { private T[] _data = new T[10]; public void AddOrUpdate(int index, T item) { if(index >= 0 && index < 10) _data[index] = item; } public T GetData(int index) { if(index >= 0 && index < 10) return _data[index]; else return default(T); } }
  • 67. Properties Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values. For example, let us have a class named Student, with private fields for name, address and phone. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields Before going on properties lets have a look at why the concept of properties came into C#? The is because of two reasons:  If the members of a class are private then how another class in C# will be able to read, write, or compute the value that field.  If the members of the class are public then another class may misuse that member.
  • 68. Properties public class Student { private string name; //field public string Name //property { get { return name; } set { name = value; } } } Properties are the special type of class members that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors.
  • 69. Accessors: The block of "set" and "get" is known as "Accessors". It is very essential to restrict the accessibility of property. There are two type of accessors i.e. get accessors and set accessors. There are different types of properties based on the "get" and set accessors: Read and Write Properties: When property contains both get and set methods. Read-Only Properties: When property contains only get method. Write Only Properties: When property contains only set method. Auto Implemented Properties: When there is no additional logic in the property accessors and it introduce in C# 3.0. The syntax for Defining Properties: <access_modifier> <return_type> <property_name> { get { // body } set { // body } } Properties
  • 70. Indexers An indexer is a special type of property that allows a class or a structure to be accessed like an array for its internal collection. C# allows us to define custom indexers, generic indexers, and also overload indexers. An indexer can be defined the same way as property with this keyword and square brackets []. Syntax <return type> this[<parameter type> index] { get{ // return the value from the specified index of an internal collection } set{ // set values at the specified index in an internal collection } }
  • 71. class IndexerExample { Private string[] valueArray = new string[3]; // Indexer declaration, this - is the keyword having a parameters list public string this[int index] { get { return valueArray[index]; } set { valueArray[index] = value; } } }
  • 72. public static void Main() { IndexerExample indexerExample = new IndexerExample(); indexerExample[0] = "first"; indexerExample[1] = "second"; indexerExample[2] = "third"; Console.Write("Printing values stored in objects used as arraysn"); Console.WriteLine("First value = {0}", ic[0]); Console.WriteLine("Second value = {0}", ic[1]); Console.WriteLine("Third value = {0}", ic[2]); }
  • 73. LINQ LINQ is 'Language Integrated Query,' and introduced in .NET Framework 3.5 to query the data from different sources of data such as collections, generics, XML documents, ADO.NET Datasets, SQL, Web Services, etc. in C# and VB.NET. LINQ provides the rich, standardized query syntax in a .NET programming language such as C# and VB.NET, which allows the developers to interact with any data sources. In C# or VB.NET, LINQ functionality can be achieved by importing the System.Linq namespace in our application. Generally, the LINQ contains a set of extension methods which allows us to query the source of data object directly in our code based on the requirement.
  • 74.
  • 75. Advantages of LINQ We do not need to learn new query language syntaxes for different sources of data because it provides the standard query syntax for the various data sources. In LINQ, we have to write the Less code in comparison to the traditional approach. With the use of LINQ, we can minimize the code. LINQ provides the compile-time error checking as well as intelligence support in Visual Studio. This powerful feature helps us to avoid run-time errors. LINQ provides a lot of built-in methods that we can be used to perform the different operations such as filtering, ordering, grouping, etc. which makes our work easy. The query of LINQ can be reused. Disadvantages of LINQ With the use of LINQ, it's very difficult to write a complex query like SQL. It was written in the code, and we cannot make use of the Cache Execution plan, which is the SQL feature as we do in the stored procedure. If the query is not written correctly, then the performance will be degraded. If we make some changes to our queries, then we need to recompile the application and need to redeploy the dll to the server.
  • 76. A query is nothing but a set of instructions. Queries are applied to the data source (i.e., in-memory object, SQL, XML, etc.) to perform the operations (i.e., CRUD operations) and show the shape of the output from that Query. This means that the Query is not responsible for what will be the output; instead, it is responsible for the shape of the output. Each Query is a combination of three things; they are: Initialization(to work with a particular data source) Condition(where, filter, sorting condition) Selection (single selection, group selection or joining)
  • 77. IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18, StandardID = 1 } , new Student() { StudentID = 2, StudentName = "Steve", Age = 21, StandardID = 1 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 18, StandardID = 2 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20, StandardID = 2 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 } }; var studentNames = studentList.Where(s => s.Age > 18) .Select(s => s) .Where(st => st.StandardID > 0) .Select(s => s.StudentName);
  • 78. using System.linq; int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; IEnumerable<int> result = from numbers in Num where numbers > 5 select numbers; //equivalent SQL Select * from Num where number > 5;
  • 79. ADO.NET ADO.NET is a part of .NET framework architecture. It is a model used by the applications to communicate with a database for manipulating data ADO.NET is a database access Technology
  • 80.
  • 81.
  • 82.
  • 83. using System.Data.SqlClient; SqlConnection con = null; try { // Creating Connection con = new SqlConnection("data source=.SQLEXPRESS; Initial Catalog=School; integrated security=True"); // Writing insert query string query = "insert into Users(Name, Age, Email, Password)" + "values('" + name.Text + "', '" + Int32.Parse(age.Text) + "', '" + email.Text + "','" + password.Text + "')"; SqlCommand sc = new SqlCommand(query, con); // Opening connection con.Open(); // Executing query int status = sc.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("OOPs, something went wrong." + ex); } // Closing the connection finally { con.Close(); }
  • 84. SqlConnection connection = null; try { connection = new SqlConnection("Data Source=.SQLEXPRESS; Initial Catalog=School; Integrated Security=True"); //db server details connection.Open(); //actual connection is opened here SqlCommand command = new SqlCommand("SELECT * from Students", connection); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Response.Write((reader.GetInt32(0) + reader.GetString(1))); } } else { Console.WriteLine("No rows found."); } reader.Close();
  • 85. connection = new SqlConnection("Data Source=.SQLEXPRESS; Initial Catalog=School; Integrated Security=True"); //db server details connection.Open(); //actual connection is opened here cmd = new SqlCommand("delete from Students where ID = " + txtrn.Text + " ", conn); cmd.ExecuteNonQuery();
  • 86. Update conn = new SqlConnection(connstring); conn.Open(); comm = new SqlCommand("update student_detail set s_name= '"+txtname.Text+"', age= "+txtage.Text+" , course=' "+txtcourse.Text+"' where roll_no = "+txtrn.Text+" ", conn); try { comm.ExecuteNonQuery(); MessageBox.Show("Updated.."); } catch (Exception) { MessageBox.Show(" Not Updated"); } finally { conn.Close(); }