Introduction To C#
Introduction To C#
C# is a new language created by Microsoft and submitted to the ECMA for standardization. This
new language was created by a team of people at Microsoft led by Anders Hejlsberg .
Hejlsberg is a Microsoft Distinguished Engineer who has created other products and languages,
including Borland Turbo C++ and Borland Delphi. With C#, they focused on taking what was
right about existing languages and adding improvements to make something better.
C# is a powerful and flexible programming language. Like all programming languages, it can be
used to create a variety of applications.
The language does not place constraints on what you can do. C# has already been used for
projects as diverse as dynamic Web sites, development tools, and even compilers.
C# syntax simplifies many of the complexities of C++ and provides powerful features such as
nullable value types, enumerations, delegates, lambda expressions and direct memory access,
which are not found in Java.
C# supports generic methods and types, which provide increased type safety and performance,
and iterators, which enable implementers of collection classes to define custom iteration
behaviors that are simple to use by client code.
C# is simple.
C# is modern.
C# is object-oriented.
In addition to Microsoft's reasons, there are other reasons to use C#:
C# Is Simple
C# removes some of the complexities and pitfalls of languages such as Java and C++,
including the removal of macros, templates, multiple inheritance, and virtual base classes.
These are all areas that cause either confusion or potential problems for C++ developers.
C# is simple because it is based on C and C++. If you are familiar with C and C++, or
even Java, you will find C# very familiar in many aspects. Statements, expressions,
operators, and other functions are taken directly from C and C++, but improvements
make the language simpler.
C# is modern
Features such as exception handling, garbage collection, extensible data types, and code
security are features that are expected in a modern language. C# contains all of these.y
other features eliminate a lot of confusion.
C# Is Modular
C# code can (and should) be written in chunks called classes, which contain routines
called member methods. These classes and methods can be reused in other applications or
programs. By passing pieces of information to the classes and methods, you can create useful,
reusable code.
C# Will Be Popular
C# is one of the newest programming languages. One of the key reasons is Microsoft and the
promises of .NET.
NULLABLE
By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)
Nullable types bridge the differences between C# types and Database types
Program without using NULL coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
if (TicketsOnSale == null)
{
AvailableTickets = 0;
}
else
{
AvailableTickets = (int)TicketsOnSale;
}
A delegate is a type safe function pointer.That is, they hold reference(Pointer) to a function.
The signature of the delegate must match the signature of the function, the delegate points to,
otherwise you get a compiler error. This is the reason delegates are called as type safe function
pointers.
A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass
in the function name as a parameter to the delegate constructor, and it is to this function the
delegate will point to.
Tip to remember delegate syntax: Delegates syntax look very much similar to a method with
a delegate keyword.
using System;
// Delegate Declaration.
public delegate void HelloFunctionDelegate(string Message);
class Pragim
{
public static void Main()
{
// Create the instance of the delegate and pass in the function
// name as the parameter to the constructor. The passed in
// function signature must match the signature of the delegate
HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
// Invoke the delegate, which will invoke the method
del("Hello from Delegte");
}
Example2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Delegate
{
public static void Main()
{
List<Employee> emplist = new List<Employee>();
emplist.Add(new Employee() { ID = 101, Name = "Mohan", Salary = 5000, Experience = 5 });
emplist.Add(new Employee() { ID = 102, Name = "Alan", Salary = 6000, Experience = 6 });
emplist.Add(new Employee() { ID = 103, Name = "Suresh", Salary = 7000, Experience = 3 });
emplist.Add(new Employee() { ID = 104, Name = "Jay", Salary = 4000, Experience = 3 });
emplist.Add(new Employee() { ID = 105, Name = "Sachin", Salary = 4500, Experience = 3 });
IsPromotable del = new IsPromotable(Promote);
Employee.PromoteEmployee(emplist,del);
Console.ReadLine();
}
public static bool Promote(Employee emp)
{
if(emp.Experience >=5)
{
return true;
}
else
{
return false;
}
}
}
delegate bool IsPromotable(Employee emp);
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }
Multicast delegate:
A Multicast delegate is a delegate that has references to more than one function. When
you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.
Approach 1:
using System;
namespace Sample
{
public delegate void SampleDelegate();
public class Sample
{
static void Main()
{
SampleDelegate del1 = new SampleDelegate(SampleMethodOne);
SampleDelegate del2 = new SampleDelegate(SampleMethodTwo);
SampleDelegate del3 = new SampleDelegate(SampleMethodThree);
// In this example del4 is a multicast delegate. You use +(plus)
// operator to chain delegates together and -(minus) operator to remove.
SampleDelegate del4 = del1 + del2 + del3 - del2;
del4();
}
Note: A multicast delegate, invokes the methods in the invocation list, in the same order in
which they are added.
If the delegate has a return type other than void and if the delegate is a multicast
delegate, only the value of the last invoked method will be returned. Along the same
lines, if the delegate has an out parameter, the value of the output parameter, will be the
value assigned by the last method.
Name space :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using projectA.teamA;
namespace namespaceexample
{
class Program
{
static void Main(string[] args)
{
classA.print();
projectA.teamB.classB.print();
}
}
}
namespace projectA
{
namespace teamA
{
class classA
{
}
}
}
namespace projectA
{
namespace teamB
{
class classB
{
public static void print()
{
Console.WriteLine("class B");
}
}
}
}
OUTPUT:
CLASSA
CLASSB
EXAMPLE2:
Allias name:
namespace namespaceexample
{
class Program
{
static void Main(string[] args)
{
PATA.classA.print();
PATB.classB.print();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Program
{
public static int NumberOfEmployees;
private static int counter;
private string name;
// A Constructor:
public Program()
{
// Calculate the employee's number:
counter = ++counter + NumberOfEmployees;
}
}
class TestEmployee
{
static void Main()
{
Program.NumberOfEmployees = 107;
Program e1 = new Program();
e1.Name = "Claude Vige";
using System;
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
var item = new SaleItem{ Name = "Shoes", Price = 19.95m };
Console.WriteLine($"{item.Name}: sells for {item.Price:C2}");
}
}
Data types
Variables are simply places to store data like numbers, strings (text), arrays of numbers or
strings, and other objects. Each variable can only store data of one type, and you
must declare variables before attempting to set or get their values.
The variables in C#, are categorized into the following types −
Value types
Reference types
Pointer types
Value Type
Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the
system allocates memory to store the value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace datatypeexample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Reference Type
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types
can refer to a memory location. If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this change in value. Example of built-
in reference types are: object, dynamic, and string.
object obj;
Example:
class ObjectTest
{
public int i = 10;
}
class MainClass2
{
static void Main()
{
object a;
a = 1; // an example of boxing
Console.WriteLine(a);
Console.WriteLine(a.GetType());
Console.WriteLine(a.ToString());
a = new ObjectTest();
ObjectTest classRef;
classRef = (ObjectTest)a;
Console.WriteLine(classRef.i);
}
}
Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for these
types of variables takes place at run-time.
dynamic d = 20;
Dynamic types are similar to object types except that type checking for object type variables
takes place at compile time, whereas that for the dynamic type variables takes place at run time.
String Type
The String Type allows you to assign any string values to a variable. The string type is an alias
for the System.String class. It is derived from object type. The value for a string type can be
assigned using string literals in two forms: quoted and @quoted.
For example,
@"Tutorials Point";
Type conversion
Type conversion is converting one type of data to another type. It is also known as Type
Casting. In C#, type casting has two forms −
namespace datatypeexample
{
class Program
{
Constant
Constants are immutable values which are known at compile time and do not change
for the life of the program. Constants are declared with the const modifier.
namespace constantexample
{
static class Constants
{
public const double Pi = 3.14159;
public const int SpeedOfLight = 300000; // km per sec.
}
class Program
{
static void Main()
{
double radius = 5.3;
Example2
the Constants are of two types
The compile time constants are declared by using the const keyword which value can not be
changed during the execution of the program.
Syntax
int const a=10;
Some key points about const variable
eg.
int const a=10;
eg.
int const a=10;
int const b=20; // correct
int const c=a+b;
int d=1;
int const c=d+b; //compile time error because d variable is the non constant into
expression.
Runtime constants (Readonly)
The Run time constants are declared by using the Readonly keyword which value can not be
changed during the execution of the program.
Syntax
int Readonly a; or
int Readonly a=0;
Some key points about const variable
Its not must to assign value at the time of declaration,we can also assign the value for
readonly through constructor.
eg.
int readonly a;
a=0;
Readonly allows, readonly constant as wel as non readonly constant variables into the
expression.
eg.
int readonly a=10;
int b=1;
int readonly c=a+b;
Readonly can be declared only at class level not inside the method.
Readonly can not be declared using static keyword because they are by default static.
Readonly constants value can be set through reference variable.
Readonly constant variable are runtime time constant variable.
DATE TIME FORMAT
using System;
class Program
{
static void Main()
{
DateTime time =
DateTime.Now; // Use
current time.
string format = "MMM ddd
d HH:mm yyyy"; // Use this
format.
Console.WriteLine(time.ToString(
format)); // Write to console.
}
}
Output
NUMBER FORMAT
double value;
value = 123;
Console.WriteLine(value.ToString("00000"));
Console.WriteLine(String.Format("{0:00000}", value));
// Displays 00123
value = 1.2;
Console.WriteLine(value.ToString("0.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0.00}", value));
// Displays 1.20
Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:00.00}", value));
// Displays 01.20
value = .56;
Console.WriteLine(value.ToString("0.0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0.0}", value));
// Displays 0.6
value = 1234567890;
Console.WriteLine(value.ToString("0,0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0,0}", value));
// Displays 1,234,567,890
value = 1234567890.123456;
Console.WriteLine(value.ToString("0,0.0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0,0.0}", value));
// Displays 1,234,567,890.1
value = 1234.567890;
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:0,0.00}", value));
// Displays 1,234.57
# CUSTOM PLACEHOLDER
double value;
value = 1.2;
Console.WriteLine(value.ToString("#.##", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture,
"{0:#.##}", value));
// Displays 1.2
value = 123;
Console.WriteLine(value.ToString("#####"));
Console.WriteLine(String.Format("{0:#####}", value));
// Displays 123
value = 123456;
Console.WriteLine(value.ToString("[##-##-##]"));
Console.WriteLine(String.Format("{0:[##-##-##]}", value));
// Displays [12-34-56]
value = 1234567890;
Console.WriteLine(value.ToString("#"));
Console.WriteLine(String.Format("{0:#}", value));
// Displays 1234567890
Console.WriteLine(value.ToString("(###) ###-####"));
Console.WriteLine(String.Format("{0:(###) ###-####}", value));
// Displays (123) 456-7890
DELEGATES EXAMPLE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace anonymoueexample
{
class Program
{
delegate int delegatetpointtoadd(int num1,int num2);
static void Main(string[] args)
{
delegatetpointtoadd s = new delegatetpointtoadd(add);
Console.WriteLine(s.Invoke(2,6).ToString());
Console.ReadLine();
}
static int add(int num1, int num2)
{
return num1 + num2;
}
}
}
Anonymous example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace anonymoueexample
{
class Program
{
delegate int delegatetpointtoadd(int num1,int num2);
static void Main(string[] args)
{
delegatetpointtoadd s = delegate(int num1, int num2)
{
return num1 + num2;
};
Console.WriteLine(s.Invoke(2,6).ToString());
Console.ReadLine();
}
// static int add(int num1, int num2)
//{
// return num1 + num2;
// }
}
}
ANANYMOUS CONVERSION:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace anonymstolamda
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("suresh");
names.Add("uma");
names.Add("umalakshmi");
string result = names.Find(searchname);
if (result == null)
Console.WriteLine("name not found");
else
Console.WriteLine("name found ");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace anonymstolamda
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("suresh");
names.Add("uma");
names.Add("umalakshmi");
string result = names.Find(delegate(string name)
{
return name.Equals("suresh");
}
);
if (result == null)
Console.WriteLine("name not found");
else
Console.WriteLine("name found ");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace anonymstolamda
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("suresh");
names.Add("uma");
names.Add("umalakshmi");
string result = names.Find(name=>name.Equals("suresh1"));
if (result == null)
Console.WriteLine("name not found.....");
else
Console.WriteLine("name found ");
}
}
}