C# Advance
C# Reflection
Reflection provides objects that describe assemblies, modules and types. By using reflection API, we can access the assembly module type and some metadata attributes on the type, which are collectively reffered to as metadata. We can use reflection to create objects dynamically, get and assign values to the object's attribute fields, and call the methods inside, including private methods.
Advantages and Disadvantages
Advantages
- Reflection can increase the flexibility and extensibility of the program.
- It helps reduce coupling and improve the adaptive ability.
- It allows to create and control the objects of any class without having hardcode to the target class in advance.
Disadvantages
- Using reflection is basically an interpreted operation and much slower for field and method access than direct code. Therefore, the mechanism is mainly used in system frameworks that require high flexity and scalability, and it is not recommended for odinary program.
- Using refelection obsures the logic inside the progeam, programmers want to see the logic of the program from the source code, but the reflection skips the technology of the source code, which would bring the maintaiance.
Example
//Using GetType to obtain type information:
int i = 42;
Type type = i.GetType();
Console.WriteLine(type);
Output
System.Int32
Thread
The term "thread" refers to a program's execution path. The control flow of each thread is unique. The threading decerases the number of wasted CPU cycles and enhances the overall performance of a program. New threads are created by the help of Threads class.
Thread class in C#
In C#, a multi-threading system is built upon the Thread class, which encapsulates the execution of the threads. This class contains a number of methods and peoperties which can help in managing and creating threads and this class is defined System.threading namespace.
Thread Life-Cycle
-
Unstarted State
It happens when a thread object is created, but the start method is not called.
-
Ready State
The ready state means the thread is ready for implemrntation but is waiting for a CPU loop.
-
Not Runnable State
This is when you have a "not runnable state" and a thread is not executable becasue of the following:
a. The sleep method has been invoked. b. The wait method has been invoked. c. I/O activities are causing a bottleneck.
-
Dead State
This state indicates the thread has beed stopped or implememted.
Example
using System;
using System.Threading;
namespace MultithreadingApplication
{
public class ThreadCreation
{
public static void CallToChildThread(){
Console.WriteLine("Child thread starts");
}
static void Main(String[] args){
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Consle.ReadKey();
}
}
}
Output
In Main: Creating the child thread
Child thread starts
Regex
Regex indicates the regular expression, the regular expresseion is a pattern of text that incldues ordinary characters (for example, letters between a and z) and special characters (callled metacharacters). Regular expressions use a single string to describe and match a series of strings that matches a syntactic rule.
Example
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main(String[] args){
// Define a regular expression for repeated words
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b"
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test String
String text = "The the quick brown fox fox jumps over the lazy dog dog.";
//Find matches
MatchCollection matches = rx.Matches(text);
//Report the number of matches found
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count,
text);
//Report on each match.
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
Console.WriteLine("'{0}' repeated at position {1} and {2}"),
groups["word"].Value,
groups[0].index,
groups[1].index);
}
}
}
Output
3 matches found in:
The the quick brown fox fox jumps over the lazy dog dog.
'The' repeated at positions 0 and 4
'fox' repeated at positions 20 and 25
'dog' repeated at positions 49 and 53
LINQ(Language Integrated Query)
LINQ(Language Integrated Query) is a language integrated query. LINQ is a set of language features and APIs that allows you to write various queries in a unfield manner. For saving and retrieving data from different data sources, eliminating the mismatch between the programming langauges and databases and providing a single query interface for different types of data sources. LINQ always use objects, so you can use the same query syntax to query and transform data in XML, object collections, SQL database, ADO.NET datasets, and any other available LINQ provider format.
Exmaple
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System. Threading.Tasks;
namespace LinqOfSelectOperation
{
class program
{
static void Main(String[] args){
int[] ints = { 5, 2, 0, 66, 4, 32, 7, 1 };
int[] intEven = ints.Where(p => p % 2 == 0).ToArray();
int[] intOdd = ints.Where(p => p % 2 != 0).ToArray();
Console.WriteLine(String.Join(" , ", intEven));
Console.WriteLine(String.Join(" , ", intOdd));
}
}
}
Output
2 , 0 , 66 , 4 , 32
5 , 7 , 1
Entity Framework
The Entity Framework is a framework ORM(object-relational mapping) that Microsoft makes available as part of the .NET developement. Its purpose is to abstract the ties to a relational database.
Entity Framework Core
Entity Framework Core is a lightweight, extensible, open source and cross-platform version of popular Entity Framework data access technology. Entity Framework Core can serve as an object-relational mapper, which:
- Enables .NET developers to work with a database using .NET objects.
- Eliminates the need for most of the data-access code that typically needs to be written.
The Model
With EF core, data access is performed using a model. A model is made up of entity classes and a context object that represents a session with the database. The context object allow querying and saving data.
EF supports the following model development approaches:
- Generate a model form an existing database.
- Hand code a model to match the database.
- Once the model is created, use EF Migrations to create the database from the model. Migrations allow evolving the databse as the mdoel changes:
Exmaple
using System.Collections.Generic;
using Microsoft.EntityFrameworkCroe;
namespace Intro;
public class BloggingContext: DbContext
{
public DbSet<Blog> Blogs{ get; set;}
public DbSet<Post> Blogs{ get; set;}
protected override void OnConfiguring(DbContextOptionsBuild optionsBuilder){
optionsBuilder.UseSqlServee(
@"Server(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True");
}
}
public class Blog
{
public int BlogId{ get; set;}
public string Url{ get; set;}
public int Rating{ get; set;}
public List<Post> Posts{ get; set;}
}
public class Post
{
public int PostId{ get; set;}
public string Title{ get; set;}
public string Content{ get; set;}
public int BlogId{ get; set;}
public Blog Blog{ get; set;}
}
Querying
Instances of your entity classes are retrieved from the database using Language Intagrated Query(LINQ).
Example
using (var db = new BloggingContext())
{
var blogs = db.Blogs
.Where(b =>b.Rating >3)
.OrderBy(b => b.Url)
.ToList();
}
Saving data
Data is created, deleted, and modified in the database using instance of your entity claases.
Example
using (var db = new BloggingContext())
{
var blog = new Blog{Url = "http://smaple.com"};
db.Blogs.Add(blog);
db.SavingChanges();
}