C#.NET
Father of C#.net- Anders
Hejlsberg
C# is pronounced
"C-Sharp".
It is an object-oriented
programming language created by Microsoft that runs on the .NET Framework.
C# has roots from the C
family, and the language is close to other popular languages like C++ and Java.
The first version was
released in year 2002. The latest version, C# 8, was released in September
2019.
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
Database applications
And much, much more!
Why Use C#?
It is one of the most popular
programming language in the world.
It is easy to learn and
simple to use.
It has a huge community
support.
C# is an object oriented
language which gives a clear structure to programs and allows code to be
reused, lowering development costs.
As C# is close to C, C++ and
Java, it makes it easy for programmers to switch to C# or vice versa.
C# Variables
Variables are containers for
storing data values.
In C#, there are different
types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without
decimals, such as 123 or -123
double - stores floating point numbers, with
decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or
'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello
World". String values are surrounded by double quotes
bool - stores values with two states: true or
false.
C# Type Casting
Type casting is when you assign a value of one data
type to another type.
In C#, there are two types of casting:
1.
Implicit Casting (automatically) - converting a smaller type to a larger type size.
char -> int -> long -> float -> double
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt);
Console.WriteLine(myDouble);
2.
Explicit Casting (manually) - converting a larger type to a smaller size type.
double -> float -> long -> int -> char
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // Convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int
Console.WriteLine(Convert.ToString(myBool));
Type Conversion Methods
It is also possible to convert data types explicitly
by using built-in methods, such as Convert.ToBoolean, Convert.ToDouble,
Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long).
Tokens
Token refers to a fundamental
unit of code that the compiler uses to understand the structure and meaning of
the source code.
Here are some examples of
tokens in C#:
1. Keywords: These are reserved words with predefined meanings
in the C# language, such as class, if, for, while, int, etc.
2. Identifiers: These are names given to entities in a program,
such as variables, functions, classes, etc. Identifiers can include letters,
digits, and underscores, but must follow certain naming conventions and cannot
be a C# keyword.
3. Literals: These are constant values explicitly specified in
the code. For example, 42 is an integer literal, "Hello" is a string
literal, true is a Boolean literal, etc.
4. Operators: These are symbols used to perform operations on
variables or values, such as +, -, *, /, &&, ||, ==, =, etc.
5. Punctuation Marks: These include symbols like parentheses
(), braces {}, square brackets [], semicolons ;, commas ,, periods ., etc.,
used for grouping, separating, or terminating code elements.
Logical operators ( AND &&, OR || , NOT EQUALTO !=)
Eg1.
Console.WriteLine("Enter 4
numbers");
int
a=Convert.ToInt32(Console.ReadLine());
int
b=Convert.ToInt32(Console.ReadLine());
int
c=Convert.ToInt32(Console.ReadLine());
if ((a > b)
&& (a > c) && (a > d))
Console.WriteLine("big=
" + a);
else if ((b
> a) && (b > c) && (b > d))
Console.WriteLine("big=
" + b);
else if (c
> d)
Console.WriteLine("big=
" + c);
else
Console.WriteLine("big=" +
d);
Console.ReadKey();
Eg2:
Console.WriteLine("Enter
a character");
char a =
Convert.ToChar(Console.ReadLine());
if((a=='a' )
|| (a=='e') || (a=='i') || (a=='o')
||(a=='u'))
{
Console.WriteLine("Vowels");
}
else {
Console.WriteLine("Not a vowel");
}
Console.ReadKey();
Assignment operators (+= , -= , *= , /= , %=)
int a =
20;
a += 3;
Console.WriteLine(a);
a -= 2;
Console.WriteLine(a);
a *= 3;
Console.WriteLine(a);
a /= 4;
Console.WriteLine(a);
a %= 2;
Console.WriteLine(a);
Console.ReadKey();
Conditional operator
Syntax:
(condition)? True:false;
Eg:
Console.WriteLine("Enter
2 numbers:");
int
a=Convert.ToInt32(Console.ReadLine());
int
b=Convert.ToInt32(Console.ReadLine());
int max = (a >
b) ? a : b;
Console.WriteLine("big=
" + max);
Console.ReadKey();
Date and Time
Console.WriteLine(DateTime.Now);
Console.WriteLine("date="
+ DateTime.Now);
Console.WriteLine("date="
+ DateTime.Now.ToLongDateString());
Console.WriteLine("date="
+ DateTime.Now.ToShortDateString());
Console.WriteLine("date="
+ DateTime.Now.ToLongTimeString());
Console.WriteLine("date="
+ DateTime.Now.Year);
Console.WriteLine("date="
+ DateTime.Now.Month);
Console.WriteLine("date="
+ DateTime.Now.Day);
Console.WriteLine("date="
+ DateTime.Now.Hour);
Console.WriteLine("date="
+ DateTime.Now.Minute);
Console.WriteLine("date="
+ DateTime.Now.Second);
String Properties
string str =
"Trivandrum";
Console.WriteLine(str);
Console.WriteLine("length="
+ str.Length);
Console.WriteLine(str.Substring(5));
Console.WriteLine(str.Substring(3,
7));
Console.WriteLine(str.Remove(3,
4));
Console.WriteLine(str.Replace("i",
"z"));
Console.WriteLine(str.PadLeft(40,
'*'));
Console.WriteLine(str.PadRight(40,
'*'));
Math Properties
Math.PI
Console.WriteLine(Math.Max(5, 10));
Console.WriteLine(Math.Min(5, 10));
Console.WriteLine(Math.Sqrt(64));
Console.WriteLine(Math.Abs(-4.7));
Console.WriteLine(Math.Round(9.99));
Loop
1.
While Loop
int i = 20;
while (i >= 0)
{
Console.WriteLine(i);
i-=2;
}
Console.ReadKey();
2.
Do…while
int i =
1;
do
{
Console.WriteLine(i);
i+=2;
} while (i <= 20);
Console.ReadKey();
3.
For loop
Console.WriteLine("Enter
a number:");
int
a=Convert.ToInt32(Console.ReadLine());
for(int
i=1;i<=10;i++)
{
Console.WriteLine(i+ "*" +a+
"=" +(i*a));
}
Console.ReadKey();
Examples:
1.
Console.WriteLine("enter
a number");
int n =
Convert.ToInt32(Console.ReadLine());
int i = 1;
do
{
Console.WriteLine("{0}*{1}={2}", i,
n, i * n);
i++;
}
while (i <= 10);
Console.ReadKey();
2.
Console.WriteLine("Enter 3
numbers:");
int
a=Convert.ToInt32(Console.ReadLine());
int
b=Convert.ToInt32(Console.ReadLine());
int
c=Convert.ToInt32(Console.ReadLine());
//int d=a+b+c;
Console.WriteLine("{0}
+ {1} + {2} = {3}" ,a,b,c,(a+b+c));
Console.ReadKey();
4. Foreach
Syntax:
Foreach(datatype
variablename in list)
{
Statements;
}
Eg1:
int[] Arrayint
={10,44,22,15};
foreach(string m in
Arrayint)
{
Console.writeLine(“” +m);
}
Eg2.
string[] Arrayint = {"Hello","how","are" ,"ÿou" };
foreach (string m in Arrayint)
{
Console.WriteLine(" " +
m);
}
Console.ReadKey();
fibinoci series
Console.WriteLine("Enter The
Limit");
int
a=Convert.ToInt32(Console.ReadLine());
int b=0;
int c=1;
Console.WriteLine(b+"\n"+c);
int d=0;
do
{
d = b + c;
if (d >=
a)
{ break; }
Console.WriteLine(d);
b = c;
c = d;
}
while (d <=
a);
What is a IL?
(IL)Intermediate Language is also known as MSIL
(Microsoft Intermediate Language) or CIL
(Common Intermediate Language). All .NET source code
is compiled to IL. This IL is then
converted to machine code at the point where the
software is installed, or at run-time by a Just-InTime (JIT) compiler.
What is a CLR?
Full form of CLR is Common Language Runtime and it
forms the heart of the .NET framework.All Languages have runtime and its the
responsibility of the runtime to take care of the code execution of the
program.For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL , Java has Java
Virtual Machine etc. Similarly .NET has CLR.Following are the responsibilities
of CLR
√ Garbage
Collection :- CLR automatically manages memory thus eliminating memory
leakes. When objects are not referred GC automatically releases those memory
thus providing efficient memory management.
√ Code
Access Security :- CAS grants rights to program depending on the
security configuration of the machine.Example the program has rights to edit or
create a new file but the security configuration of machine does not allow the
program to delete a file.CAS will take care that the code runs under the
environment of machines security configuration.
√ Code Verification :- This ensures
proper code execution and type safety while the code runs.It prevents the
source code to perform illegal operation such as accessing invalid memory
locations etc.
√ IL( Intermediate language )-to-native
translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine
code and then executes. CLR also determines depending on platform what is
optimized way of running the IL code.
What is a CTS?
In order that two language communicate smoothly CLR
has CTS (Common Type System).Example in VB you have “Integer” and in C++ you
have “long” these datatypes are not compatible so the interfacing between them
is very complicated. In order 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.CLS
which is covered in the coming question is subset of CTS.
What is a CLS(Common Language Specification)?
This is a
subset of the CTS which all .NET languages are expected to support.It was
always a dream of microsoft to unite all different languages in to one umbrella
and CLS is one step towards that.Microsoft has defined CLS which are nothing
but guidelines that language to follow so that it can communicate with other
.NET languages in a seamless manner
Array
Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for each value.
string[] cars = { "Volvo",
"BMW", "Ford", "Mazda" };
Console.WriteLine(cars[1])
Console.WriteLine(cars.Length);
LINQ(Language Integrated Query)
Array methods,
such as Min, Max, and Sum, can be found in the System.Linq namespace.
int[] myNumbers = { 5, 1, 8,
9 };
Console.WriteLine(myNumbers.Max()); // returns the largest value Console.WriteLine(myNumbers.Min()); // returns the smallest value
Console.WriteLine(myNumbers.Sum()); // returns the sum of elements
Eg:
//Write a C# program to compute
the sum of all the elements of an array of integers.
internal class Program
{
static void
Main(string[] args)
{
int sum
= 0 ;
Console.WriteLine("Enter
limit:");
int
num=Convert.ToInt32(Console.ReadLine());
int[]
numArray = new int[num];
Console.WriteLine("Enter
" + num + " numbers:");
for(int i =
0; i < numArray.Length; i++)
{
numArray[i] =
Convert.ToInt32(Console.ReadLine());
sum = sum + numArray[i];
}
Console.WriteLine("Numbers
are");
for (int i =
0; i < numArray.Length; i++)
{
Console.WriteLine(numArray[i]);
}
Console.WriteLine("Sum="+sum);
Console.ReadKey();
}
}
}
C# Methods
A method is a block of code which only runs when it is
called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they
are also known as functions.
Why use methods? To reuse code: define the code once,
and use it many times.
Eg:
static void
MyMethod()
{
Console.WriteLine("I just
got executed!");
}
static void
MyMethod1(string fname)
{
Console.WriteLine(fname + "
Refsnes");
}
static int
sum(int a,int b)
{
return a + b;
}
static double
area(double radius)
{
return Math.PI *
radius * radius;
}
static void
Main(string[] args)
{
Console.WriteLine("Enter
Radius:");
double
r=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Area="+area(r));
MyMethod();
MyMethod1("anchu");
Console.WriteLine("Enter
2 numbers:");
int c =
Convert.ToInt32(Console.ReadLine());
int d =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine(sum(c, d));
}
C# - What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or
methods that perform operations on the data, while object-oriented programming
is about creating objects that contain both data and methods.
Object-oriented programming has several advantages
over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the C# code DRY "Don't Repeat
Yourself", and makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable
applications with less code and shorter development time
THE FOLLOWINGS ARE THE FEATURES OF OOPS:
1.Class
2.Objects
3.Encapsulation
4.Abstraction
5.Inheritance
6.polymophism
Class -class is a group of similar objects.Class is a way to bind data
describing an entity and assossiated functions together.
Object –object is an identifier entity that have some
characteristics and behavior.
Abstraction-It is a concept of simplifying a real world object
into its essential features without including background details.
Encapsulation-Wrapping up of data into single unit is known as
encapsulation.
Inheritance –It is a property of inheriting properties of one
class to another.
Polymorphism-The word polymorphism means having many forms. In
object-oriented programming paradigm, polymorphism is often expressed as 'one
interface, multiple functions'.
Polymorphism can be static or dynamic. In static
polymorphism, the response to a function is determined at the compile time.
In dynamic polymorphism, it is decided at run-time.
POLYMORPHISM-"Poly"
means many and "morph" means forms. Polymorphism provides the ability
to a class to have multiple implementations with the same name.
Class
Syntax
Classname objectname= new classname();
Eg: Program
p= new Program();
1. internal class Program
{
string
color = "Red";
public void
show()
{
Console.WriteLine("Welcome");
}
public int
sum(int a,int b)
{
return a+
b;
}
static void
Main(string[] args)
{
//class and
object
Program p= new
Program();
Console.WriteLine(p.color);
p.show();
Console.WriteLine("Enter
2 numbers");
int
a=Convert.ToInt32(Console.ReadLine());
int
b=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sum
="+p.sum(a,b));
Console.ReadKey();
}}
//Variable
declared outside void main()
2. internal class Program
{
string name;
static void
Main(string[] args)
{
//class and
object
Program p= new
Program();
p.name = "Anchu";
Console.WriteLine(p.name);
Console.ReadKey();
}
Inheritance (Derived and
Base Class)
In C#, it is possible to inherit fields and methods from one class
to another. We group the "inheritance concept" into two categories:
Derived Class (child) - the class that inherits from another class
Base Class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In C#, there are several types of inheritance:
In C#, there are 4 types of inheritance:
Single inheritance
A derived class that inherits from only one base
class.
Eg:
class Vehicle // base class (parent)
{
public string
brand = "Ford";
// Vehicle field
public void
hone() //
Vehicle method
{
Console.WriteLine("keyyyy……...!");
}
}
internal class Program:Vehicle
{
public string
modelname = " EcoSport";
static void
Main(string[] args)
{
Program p= new
Program();
p.hone();
Console.WriteLine(p.brand);
Console.WriteLine(p.modelname);
Console.ReadKey();
}
}
Multi-level inheritance
A derived class
that inherits from a base class and the derived class itself becomes the base
class for another derived class.
class travels
{
public string car
= "Tata";
public void
drive()
{
Console.WriteLine("Driving");
}
}
class Vehicle:travels
{
public string
brand = "Ford";
public void
hone()
{
Console.WriteLine("keyyyy……...!");
}
}
internal class Program:Vehicle
{
public string
modelname = " EcoSport";
static void
Main(string[] args)
{
Program p= new
Program();
p.hone();
Console.WriteLine(p.brand);
Console.WriteLine(p.modelname);
Console.WriteLine(p.car);
p.drive();
Console.ReadKey();
}
Hierarchical inheritance
A base class
that serves as a parent class for two or more derived classes.
Syntax:
class derived-class : base-class
{
// methods
and fields
.
.
}
eg: class animal
{
public string
wild = "Lion";
}
class dog:animal
{
public void
bark()
{
Console.WriteLine("boww");
}
}
class cat:animal
{
public void
sound()
{
Console.WriteLine("Maew");
}
}
internal class Program
{
static void
Main(string[] args)
{
cat c=new
cat();
c.sound();
Console.WriteLine(c.wild);
dog d = new
dog();
d.bark();
Console.WriteLine(d.wild);
Console.ReadKey();
}
}
Multiple inheritance: A derived class that inherits from two or more base
classes.
Hybrid inheritance
Hybrid inheritance is a combination of two or more
types of inheritance. The combination of multilevel and hierarchical
inheritance is an example of Hybrid inheritance.
namespace
Hybridinheritance
{
internal class Program
{
class A
{
public void
fooA()
{
Console.WriteLine("
CLASS A");
}
}
//Derived Class
class B : A
{
public void
fooB()
{
Console.WriteLine("
CLASS B");
}
}
class C : A
{
public void
fooC()
{
Console.WriteLine("
CLASS C");
}
}
//Derived Class
class D : C
{
public void
fooD()
{
Console.WriteLine("
CLASS D");
}
}
//Derived Class
class E : C
{
public void
fooE()
{
Console.WriteLine("
CLASS E");
}
}
//Derived Class
class F : B
{
public void fooF()
{
Console.WriteLine("
CLASS F");
}
}
//Derived Class
class G : B
{
public void
fooG()
{
Console.WriteLine("
CLASS G");
}
}
static void
Main(string[] args)
{
G ob = new
G();
ob.fooA();
ob.fooB();
ob.fooG();
F OB1 = new
F();
OB1.fooF();
D ob2 = new
D();
ob2.fooD();
ob2.fooC();
Console.ReadKey();
}
}
}
Types of Polymorphism
There are two types of
polymorphism in C#:
Static / Compile Time
Polymorphism.
Dynamic / Runtime
Polymorphism.
Method overloading is an
example of Static Polymorphism. In overloading, the method / function has a
same name but different signatures.
Static Polymorphism
The mechanism of linking a
function with an object during compile time is called early binding. It is also
called static binding. C# provides two techniques to implement static
polymorphism. They are −
Function overloading
Operator overloading
namespace
Polymorphism
{
public class TestData
{
public int
Add(int a, int b, int c)
{
return a +
b + c;
}
public int
Add(int a, int b)
{
return a +
b;
}
}
internal class Program
{
static void
Main(string[] args)
{
TestData dataClass = new
TestData();
int
add2 = dataClass.Add(45, 34, 67);
int
add1 = dataClass.Add(23, 34);
Console.WriteLine(add2);
Console.WriteLine(add1);
Console.ReadKey();
}
}
}
Method overriding
Method overriding can be done using
inheritance. With method overriding it is possible for the base class and
derived class to have the same method name and same something.
namespace
overridding
{
class baseClass
{
// show() is
'virtual' here
public virtual void
show()
{
Console.WriteLine("Base
class");
}
}
// class 'baseClass' inherit
// class 'derived'
class derived :
baseClass
{
//'show()' is
'override' here
public override void
show()
{
Console.WriteLine("Derived
class");
}
}
internal class Program
{
static void
Main(string[] args)
{
baseClass obj;
obj = new
baseClass();
obj.show();
obj = new
derived();
obj.show();
Console.ReadKey();
}
}
}
C# | Interface
In C#, an interface can be defined using the interface
keyword. An interface can contain declarations of methods, properties,
indexers, and events.
• 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.
Syntax for Interface Declaration:
interface
<interface_name >
{
// declare Events
// declare
indexers
// declare
methods
// declare
properties
}
Syntax for Implementing Interface:
class class_name : interface_name
Eg: namespace ConsoleApp42
{
interface Myinterface
{
void
display();//method declaration
}
interface Myinterface2
{
void
show();
}
class Myclass:Myinterface,Myinterface2
{
public void
display()
{
Console.WriteLine("Hello");
}
public void
show()
{
Console.WriteLine("Show");
}
}
internal class Program:Myclass
{
static void
Main(string[] args)
{
Program p= new
Program();
p.display();
p.show();
Console.ReadKey();
}
}
}
No comments:
Post a Comment