Data Types in C#
Const and Read-Only
Constants are the immutable values that are known at the time of program compilation and do not change
their values for the lifetime of the program. The Read-only variables are also immutable values but these
values are known at runtime and also do not change their values for the life of the program.
1. The keyword const is used to create a “constant” variable. It means it will create a variable whose
value is never going to be changed. In simple words, we can say that the variable whose value cannot
be changed or modified once after its declaration is known as a constant variable.
2. Constants are static by default.
3. It is mandatory to initialize a constant variable at the times of its declaration.
4. The behavior of a constant variable is same as the behavior of static variable i.e. maintains only one
copy in the life cycle of class and initialize immediately once the execution of the class start (object not
required)
5. The only difference between a static and constant variable is that the static variable value can be
modified but a constant variable value can never be modified.
whenever we declare a constant variable, the C# compiler substitutes its value directly into the
Intermediate Language (MSIL).
Read-only Variable in C#:
1. The variable which is declared by using the readonly keyword is known as a read-only variable. The
read-only variable’s value cannot be modified once after its initialization.
2. It is not mandatory or required to initialize the read-only variable at the time of its declaration like a
constant. You can initialize the read-only variables under a constructor but the most important point is
that once after initialization, you cannot modify the value.
3. The behavior of a read-only variable is similar to the behavior of a non-static variable. That is, it
maintains a separate copy for each object. The only difference between these two is non-static
variables can be modified while the read-only variables cannot be modified.
4. A constant variable is a fixed value for the complete class whereas a read-only variable is a fixed value
but specific to one object of the class.
5.
6. namespace ReadOnlyDemo
7. {
8. class ReadOnlyExample
9. {
10. public readonly int number = 5;
11. }
12.
13. class Program
14. {
15. static void Main(string[] args)
16. {
17. ReadOnlyExample readOnlyInstance = new ReadOnlyExample();
18. [Link]([Link]);
19.
20. [Link]("Press any key to exist.");
21. [Link]();
22. }
23. }
24. }
الحظ ان الكونست ستاتيك ومينعش اغير قيمتها نهائيا لكن الريد اونلى مش ستاتيك ومينفعش اغير قيمتها فى الرن تيم ولكن ينفع لغير قيمتها فى الكونستركتور
بس مش فى اى مكان تانى فى البروجكت
Dynamic Types
Dynamic that avoids compile-time type checking. A dynamic type escapes type
checking at compile-time; instead, it resolves type at run time.
Stack and Heap in C#
What Is Object-Oriented Programming?
Encapsulation in C# with Examples
Data encapsulation is also called data hiding because by using this principle we can hide the internal data
from outside the class.
In C# encapsulation is implemented
1. By declaring the variables as private (to restrict its direct access from outside the class)
2. By defining one pair of public setter and getter methods or properties to access private variables.
C# Abstract
Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide the
internal details and showing functionality only. Abstraction can be achieved by two ways:
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
Abstract Method
A method which is declared abstract and has no body is called abstract method. It can be declared
inside the abstract class only. Its implementation must be provided by derived classes. For example:
Tuples in C#
Tuples in C# 7, provides a better mechanism to return multiple values from a method.
using System;
using [Link];
namespace TulesDemo
{
class Program
{
static void Main()
{
var values = new List<double>() { 10, 20, 30, 40, 50 };
Tuple<int, double> t = Calulate(values);
[Link]($"There are {t.Item1} values and their sum is {t.Item2}");
[Link]();
}
//Declaring the return type as Tuple<int, double>
private static Tuple<int, double> Calulate(IEnumerable<double> values)
{
int count = 0;
double sum = 0.0;
foreach (var value in values)
{
count++;
sum += value;
}
//Creating an object of Tuple class by calling the static Create method
Tuple<int, double> t = [Link](count, sum);
//Returning the tuple instance
return t;
}
}
}
using System;
using [Link];
namespace TulesDemo
{
class Program
{
static void Main()
{
var values = new List<double>() { 10, 20, 30, 40, 50 };
var (countResult, SumResult) = Calulate(values);
var result= Calulate(values);
[Link]($"There are {countResult} values and their sum is {SumResult}");
[Link]($"There are {[Link]} values and their sum is {[Link]}");
[Link]();
}
private static (int count, double sum) Calulate(IEnumerable<double> values)
{
int count = 0;
double sum = 0.0;
foreach (var value in values)
{
count++;
sum += value;
}
return (count, sum);
}
}
}
Local Functions
is introduced as part of C# 7. The Local Functions means a function is declared and defined inside
another function
class Program
{
static void Main()
{
int a = 10, b = 5;
int sum = Sum(a, b);
int difference = Difference(a, b);
[Link]($"The Sum of {a} and {b} is {sum}");
[Link]($"The Difference of {a} and {b} is {difference}");
int Sum(int x, int y)
{
return x + y;
}
int Difference(int x, int y)
{
return x - y;
}
[Link]("Press any key to exit.");
[Link]();
}
asynchronous programming
Generalized Async Return Types
1. Task<TResult>, this return is used when the async method that returns a value.
2. Task, this return type is used when the async method does not return any value.
3. void, this return type is used for an event handler.
The async method returning Task<T>
4. public class Example
5. {
6. public static void Main()
7. {
8. [Link](ShowTodaysInfo().Result);
9.
10. [Link]("Press any key to exist.");
11. [Link]();
12. }
13.
14. private static async Task<string> ShowTodaysInfo()
15. {
16. string ret = $"Today is {[Link]:D}\n" +
17. "Today's hours of leisure: " +
18. $"{await GetLeisureHours()}";
19. return ret;
20. }
21.
22. static async Task<int> GetLeisureHours()
23. {
24. // [Link] is a placeholder for actual work that returns a string.
25. var today = await [Link]<string>([Link]());
26.
27. // The method then can process the result in some way.
28. int leisureHours;
29. if ([Link]() == 'S')
30. leisureHours = 16;
31. else
32. leisureHours = 5;
33.
34. return leisureHours;
35. }
36. }
37.
The async method returning Task
public class Example
{
public static void Main()
{
DisplayCurrentInfo().Wait();
[Link]("Press any key to exist.");
[Link]();
}
static async Task DisplayCurrentInfo()
{
await WaitAndApologize();
[Link]($"Today is {[Link]:D}");
[Link]($"The current time is {[Link]:t}");
[Link]("The current temperature is 76 degrees.");
}
static async Task WaitAndApologize()
{
// [Link] is a placeholder for actual work.
await [Link](2000);
// [Link] delays the following line by two seconds.
[Link]("\nSorry for the delay. . . .\n");
}
}
Expression Bodied Members in C#
public class Employee
{
private string FirstName;
private string LastName;
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string GetFullName() => $"{FirstName} {LastName}";
public override string ToString() => $"{FirstName} {LastName}";
public void DisplayName() => [Link](GetFullName());
}
class Program
{
static void Main()
{
Employee employee = new Employee("Pranaya", "Rout");
[Link]();
[Link](employee);
[Link]("Press any key to exists");
[Link]();
}
}
public class Location
{
private string locationName;
public Location(string name) => locationName = name;
public string Name
{
get => locationName;
set => locationName = value;
}
}
class Program
{
static void Main()
{
Location location = new Location("Mumbai");
[Link]([Link]);
[Link]("Press any key to exists");
[Link]();
}
}
Delegates
the delegates in C# are the Type-Safe Function Pointer. It means they hold the reference of a method or
function and then calls that method for execution.
How many ways we can call a method in C#?
In C#, we can call a method that is defined in a class in two ways. They are as follows:
1. We can call the method using the object of the class if it is a non-static method or we can call the
method through class name if it is a static method.
2. We can also call a method in C# by using delegates. Calling a C# method using delegate will be faster
in execution as compared to the first process i.e. either by using an object or by using the class name.
Types of delegates
1. Single cast delegate
2. Multicast delegate
If a delegate is used for invoking a single method then it is called a single cast delegate or unicast
delegate
If a delegate is used for invoking multiple methods then it is known as the multicast delegate. Or the
delegates that represent more than one function are called Multicast delegate.
Single cast delegate example
namespace DelegateDemo
{
//Defining Delegates
//Note: The access specifeis, return type and the number, order and type of parameters of
delegate
//should be same as the function it refers to.
public delegate void AddDelegate(int a, int b);
public delegate string GreetingsDelegate(string name);
public class Program
{
//Defining Methods
//NonStatic method
public void Add(int x, int y)
{
[Link](@"The Sum of {0} and {1}, is {2} ", x, y, (x + y));
}
//Static Method
public static string Greetings(string name)
{
return "Hello @" + name;
}
static void Main(string[] args)
{
Program obj = new Program();
//Instantiating delegate by passing the target function Name
//The Add method is non static so here we are calling method using object
AddDelegate ad = new AddDelegate([Link]);
//Greetings method is static so here we are callling the method by using the class name
GreetingsDelegate gd = new GreetingsDelegate([Link]);
//Invoking The Delegates
ad(100, 50);
string GreetingsMessage = gd("Pranaya");
//We can also use Invoke method to execute delegates
// [Link](100, 50);
// string GreetingsMessage = [Link]("Pranaya");
[Link](GreetingsMessage);
[Link]();
}
}
}
Multicast Delegate
A Multicast Delegate is a delegate that holds the references of more than one function. When we invoke
the multicast delegate, then all the functions which are referenced by the delegate are going to be
invoked. If you want to call multiple methods using a delegate then all the method signature should be
the same.
namespace MulticastDelegateDemo
{
public delegate void RectangleDelete(double Width, double Height);
public class Rectangle
{
public void GetArea(double Width, double Height)
{
[Link](@"Area is {0}", (Width * Height));
}
public void GetPerimeter(double Width, double Height)
{
[Link](@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
RectangleDelete rectDelegate = new RectangleDelete([Link]);
//RectangleDelete rectDelegate = [Link];
//binding a method with delegate object
// In this example rectDelegate is a multicast delegate. You use += operator
// to chain delegates together and -= operator to remove.
rectDelegate += [Link];
rectDelegate(23.45, 67.89);
[Link]();
[Link](13.45, 76.89);
[Link]();
//Removing a method from delegate object
rectDelegate -= [Link];
[Link](13.45, 76.89);
[Link]();
}
}
}
namespace MulticastDelegateDemo
Another approach to Create Multicast Delegates in C#.
{
public delegate void MathDelegate(int No1, int No2);
public class Program
{
public static void Add(int x, int y)
{
[Link]("THE SUM IS : " + (x + y));
}
public static void Sub(int x, int y)
{
[Link]("THE SUB IS : " + (x - y));
}
public void Mul(int x, int y)
{
[Link]("THE MUL IS : " + (x * y));
}
public void Div(int x, int y)
{
[Link]("THE DIV IS : " + (x / y));
}
static void Main(string[] args)
{
Program p = new Program();
MathDelegate del1 = new MathDelegate(Add);
MathDelegate del2 = new MathDelegate([Link]);
MathDelegate del3 = [Link];
MathDelegate del4 = new MathDelegate([Link]); ;
//In this example del5 is a multicast delegate. We can use +(plus)
// operator to chain delegates together and -(minus) operator to remove.
MathDelegate del5 = del1 + del2 + del3 + del4;
[Link](20, 5);
[Link]();
del5 -= del2;
del5(22, 7);
[Link]();
}
}
}
Multicast Delegates with Return Type in C#:
If the delegate has a return type other than void and if the delegate is a multicast delegate. then 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.
namespace MulticastDelegateDemo
{
// Deletegate's return type is int
public delegate int SampleDelegate();
public class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(MethodOne);
del += MethodTwo;
// The ValueReturnedByDelegate will be 2, returned by the MethodTwo(),
// as it is the last method in the invocation list.
int ValueReturnedByDelegate = del();
[Link]("Returned Value = {0}", ValueReturnedByDelegate);
[Link]();
}
// This method returns one
public static int MethodOne()
{
return 1;
}
// This method returns two
public static int MethodTwo()
{
return 2;
}
}
}
By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any
method that matches this signature, to the delegate and it will be called each time my delegate is
called".
using System;
using [Link];
namespace DelegateRealtimeExample
{
public delegate bool EligibleToPromotion(Employee EmployeeToPromotion);
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Experience { get; set; }
public int Salary { get; set; }
public static void PromoteEmployee(List<Employee> lstEmployees, EligibleToPromotion
IsEmployeeEligible)
{
foreach (Employee employee in lstEmployees)
{
if (IsEmployeeEligible(employee))
{
[Link]("Employee {0} Promoted", [Link]);
}
}
}
}
public class Program
{
static void Main()
{
Employee emp1 = new Employee()
{
ID = 101,
Name = "Pranaya",
Gender = "Male",
Experience = 5,
Salary = 10000
};
Employee emp2 = new Employee()
{
ID = 102,
Name = "Priyanka",
Gender = "Female",
Experience = 10,
Salary = 20000
};
Employee emp3 = new Employee()
{
ID = 103,
Name = "Anurag",
Experience = 15,
Salary = 30000
};
List<Employee> lstEmployess = new List<Employee>();
[Link](emp1);
[Link](emp2);
[Link](emp3);
EligibleToPromotion eligibleTopromote = new EligibleToPromotion([Link]);
[Link](lstEmployess, eligibleTopromote);
[Link]();
}
public static bool Promote(Employee employee)
{
if ([Link] > 10000)
{
return true;
}
else
{
return false;
}
}
}
}
Generic Delegate
Anonymous Method
namespace DelegateDemo
{
public class AnonymousMethods
{
public delegate string GreetingsDelegate(string name);
static void Main(string[] args)
{
string Message = "Welcome to Dotnet Tutorials";
GreetingsDelegate gd = delegate(string name)
{
return "Hello @" + name + " " + Message;
};
string GreetingsMessage = [Link]("Pranaya");
[Link](GreetingsMessage);
[Link]();
}
}
}
Func Delegate
built-in generic delegate
Action Delegate
An Action type delegate is the same as Func delegate except that the Action
delegate doesn't return a value. In other words, an Action delegate can be used
with a method that has a void return type.
Predicate Delegate
It represents a method containing a set of criteria and checks whether the
passed parameter meets those criteria. A predicate delegate methods must take
one input parameter and return a boolean - true or false.
Anonymous Method
An anonymous method is a method without a name. Anonymous methods in C#
can be defined using the delegate keyword and can be assigned to a variable of
delegate type.
Events
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system
generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events
are used for inter-process communication.
The events are declared and raised in a class and associated with the event handlers using delegates
within the same class or some other class. The class containing the event is used to publish the event.
This is called the publisher class. Some other class that accepts this event is called
the subscriber class. Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The event-delegate
association is also defined in this object. A publisher class object invokes the event and it is notified to
other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the
publisher class invokes the method (event handler) of the subscriber class.
C# Generic & Non-generic Collections
[Link] namespace contains the non-generic collection types
[Link] namespace includes generic collection types.
ArrayList
is a non-generic collection of objects whose size increases dynamically. It is the
same as Array except that its size increases dynamically.
ArrayList arlist = new ArrayList();
// or
var arlist = new ArrayList();
List<T>
Accessing a List using LINQ
The List<T> implements the IEnumerable interface. So, we can query a list using LINQ query syntax or
method syntax, as shown below.
SortedSet<T>
It maintains ascending order and does not store duplicate elements. It is suggested to use SortedSet
class if you have to store unique elements and maintain ascending order. It is found in
[Link] namespace.
using [Link];
public class SortedSetExample
{
public static void Main(string[] args)
{
var names = new SortedSet<string>();
[Link]("Sonoo");
[Link]("Ankit");
foreach (var name in names)
{
[Link](name);
}
}
Dictionary<TKey, TValue>
Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no
particular order.
using [Link];
public class Program
{
public static void Main()
{
IDictionary<int, string> numberNames = new Dictionary<int, string>();
[Link](1, "One"); //adding key/value using the Add() method
[Link](3, "Three");
[Link](2, "Two");
foreach (KeyValuePair<int, string> kvp in numberNames)
[Link]("Key: {0}, Value: {1}", [Link], [Link]);
//creating a dictionary using collection-initializer syntax
var cities = new Dictionary<string, string>(){
{"UK","London, Manchester, Birmingham"},
{"USA","Chicago, New York, Washington"},
{"India","Mumbai, New Delhi, Pune"}
};
foreach (var kvp in cities)
[Link]("Key: {0}, Value: {1}", [Link], [Link]);
}
}
Hashtable
is a non-generic collection that stores key-value pairs, similar to
generic Dictionary<TKey, TValue> collection. It optimizes lookups by computing
the hash code of each key and stores it in a different bucket internally and then
matches the hash code of the specified key at the time of accessing values.
using [Link];
public class Program
{
public static void Main()
{
Hashtable numberNames = new Hashtable();
[Link](1, "One"); //adding a key/value using the Add() method
[Link](2, "Two");
[Link](3, "Three");
//The following throws run-time exception: key already added.
//[Link](3, "Three");
foreach (DictionaryEntry kvp in numberNames)
[Link]("Key: {0}, Value: {1}", [Link], [Link]);
//creating a dictionary using collection-initializer syntax
var cities = new Hashtable(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach (DictionaryEntry kvp in cities)
[Link]("Key: {0}, Value: {1}", [Link], [Link]);
}
}