Category: C#

C# 7 Local Functions

C# 6 Local functions are useful to create helper methods and was written as below-

 
public class LocalFunctions
{
    public int Age { get; set; }

    public string C6PrivateFunction()
    {
       return $"C#6 ==> Person is {GetEligibility(Age)}";
    }        
}

private string GetEligibility(int age)
{
   return age > 18 ? "Adult" : "Youth";
}

With C# 7.0 the same can be written as below.

Inside local functions, variables and parameters from the enclosing scope are also available and the same can also be written using as expression body.

        
public string C7LocalFunction()
{
   return $"C#7 ==> Person is {GenerateEligibility(Age)}";

   string GenerateEligibility(int age)
   {
      return age > 18 ? "Adult" : "Youth";
   }
}

public string C7LocalFunction1()
{
   return $"C#7 ==> Person is {GenerateEligibility(Age)}";

   string GenerateEligibility(int age) =>  age > 18 ? "Adult" : "Youth";
}

Enjoy coding!!!

C# 7.0 – Throw expressions

C# 7.0 introduced throw expression, throwing exception has always been a statement and need to call a method to throw exception. Syntax is same as you’ve always used to throw exceptions difference is it can be also placed in the conditional expressions

With c# 7.0 exceptions can be thrown directly from within expression as shown below-

 public class ThrowExpressions
 {
 public static string ThrowExpressionMethod(string someString)
 {
 return string.IsNullOrWhiteSpace(someString) ? throw new ArgumentNullException("someString is empty") : someString;
 }
 }

 

 

 

 

C# 7.0 Numerical literals and OUT variables

Numeric literal syntax

Reading numbers makes it difficult to understand code. C# 7 has improvement done on the digit separator.

public static int IntegerLiterals()
 { return 1_000_000; }

public static double DoubleLiterals()
 { return 9_8_7.1_2_3; }

public static int BinaryLiterals()
 { return 0b0001_0000; }

 Console.WriteLine($" One Million : {NumericalLiterals.IntegerLiterals()}");
 Console.WriteLine($" Double : {NumericalLiterals.DoubleLiterals()}");
 Console.WriteLine($" Binary to Decimal : {NumericalLiterals.BinaryLiterals()}");

Output:

One Million : 1000000
Double : 987.123
Binary to Decimal : 16

 

Inline out variables

Earlier declaring out variables has to be done separately. Now this can be done in line as follows

public static int InlineOutVariables()
 {
 string input = "100";
 if (!int.TryParse(input, out int result))
 {
 return 0;
 }
 return result;
 }

You can declare out variable where you use it.  The declared out variables also leaks out of the if statement scope and used later.

 

 

Entity Framework – Code First DB migration

Code first is useful in Domain Driven Design.Code first use Convention based migration- it is a set of rules to automatically configure a conceptual model based on domain class definition.
Type Discovery- Code first approach generates classes for the properties set in DBSet and also includes referenced types that are included in classes, even if referenced types are defined in another assembly.
The conventions for the type discovery are:

  1. Code-First includes types defined as a DbSet property in context class.
  2. Code-First includes reference types included in entity types even if they are defined in different assembly.
  3. Code-First includes derived classes even if only the base class is defined as DbSet property.

Assuming entities are created and DBContext is set along with the DB Connection string to enable migration use –
enable-migration command in package manager console.once the migrations are enabled Migrations folder is created with the InitalCreate.cs class. Any further changes to the model a version of changes are created with a Up() and down() method which helps to Migrate and Rollback the model changes to database.
To update the last changes to the DB use add-migration “migration title” and update-database command in console.This should now update or create Initial tables and changed schema. Along side this a Seed() method is called. You may need to add the initial/sample data to tables use the context for same in Seed() method.
To Rollback the changes use update-database -targetmigration “migration title”. I find this a bit confusing initially but what this command does is it takes back the database state to the last best migration performed rollingback the latest changes performed.
While doing so you may receive error-Unable to generate an explicit migration because the following explicit migrations are pending: [201704251318501_migrationname]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
This seems to complaining about the migration which are performed where a version is missing. So migrations has to be happen in a sequence of it was created.

Hope this helps.

List of LINQ syntax for immediate execution

These are some of the LINQ syntax for immediate query execution (more to add)-
1. ToList()

2. FirstOrDefault

3. Aggregate Methods (like Count(), Sum() etc.)

4. AsEnumerable()

As I said there are more to add, will keep updating as and when I find more methods.


Happy Coding!!!