CSharp - Other

Declare an Empty Array

Use the “new” Keyword


The Array Initializer Syntax

var myArray = new string[0];


Use an Empty String Literal

var myArray = new string[] { };

or

string[] myArray = { };



Use the Enumerable Class


Use the Empty Method

var myArray = Enumerable.Empty<string>().ToArray();


Use the Repeat Method

var myArray = Enumerable.Repeat("", 0).ToArray();

or

var myArray = Enumerable.Repeat(string.Empty, 0).ToArray();



Use the Array Class


var myArray = Array.Empty<string>();

Delete --- Referrer-Policy

The Referrer-Policy HTTP header controls how much referrer information (sent with the Referer header) should be included with requests. Aside from the HTTP header, you can set this policy in HTML.


Syntax

Referrer-Policy: no-referrer
Referrer-Policy: no-referrer-when-downgrade
Referrer-Policy: origin
Referrer-Policy: origin-when-cross-origin
Referrer-Policy: same-origin
Referrer-Policy: strict-origin
Referrer-Policy: strict-origin-when-cross-origin
Referrer-Policy: unsafe-url


Directives

  • no-referrer - The Referrer header will be omitted: sent requests do not include any referrer information.
  • no-referrer-when-downgrade - Send the origin, path, and query string in Referrer when the protocol security level stays the same or improves (HTTP → HTTP, HTTP → HTTPS, HTTPS → HTTPS). Don't send the Referrer header for requests to less secure destinations (HTTPS → HTTP, HTTPS → file).
  • origin - Send only the origin in the Referrer header. For example, a document at https://example.com/page.html will send the referrer https://example.com/.
  • origin-when-cross-origin - When performing a same-origin request to the same protocol level (HTTP → HTTP, HTTPS → HTTPS), send the origin, path, and query string. Send only the origin for cross origin requests and requests to less secure destinations (HTTPS → HTTP).
  • same-origin - Send the origin, path, and query string for same-origin requests. Don't send the Referrer header for cross-origin requests.
  • strict-origin - Send only the origin when the protocol security level stays the same (HTTPS → HTTPS). Don't send the Referrer header to less secure destinations (HTTPS → HTTP).
  • strict-origin-when-cross-origin (default) - Send the origin, path, and query string when performing a same-origin request. For cross-origin requests send the origin (only) when the protocol security level stays same (HTTPS → HTTPS). Don't send the Referrer header to less secure destinations (HTTPS → HTTP).


Integration with HTML

You can also set referrer policies inside HTML. For example, you can set the referrer policy for the entire document with a <meta> element with a name of referrer:

<meta name="referrer" content="origin" />


You can specify the referrerpolicy attribute on <a>, <area>, <img>, <iframe>, <script>, or <link> elements to set referrer policies for individual requests:

<a href="http://example.com" referrerpolicy="origin">…</a>


Alternatively, you can set a noreferrer link relation on an a, area, or link elements:

<a href="http://example.com" rel="noreferrer">…</a>

Difference between Parse / TryParse / ParseExact / TryParseExact

Parse

int.Parse("12.44");

Exception : Above code will generate the exception Input string was not in a correct format, just because you are trying to cast float / real value in Integer. Only it is parsing if your parameter value must match the desire type in which you are trying to parse.



TryParse

case #1
int.TryParse("14.55",out a);

case #2
int.TryParse("14", out a);

Output : Above code (case 1) will return false, just because parsing operation gets failed and value for variable 'a' would be 'zero'. Here consider 'a' is output type of parameter like we have in Oracle / SQL Server (not exactly same but behavior is same). If parsing get succeeded than it will return true and target variable (i.e. 'a') will have the parsed value, like in code (case 2), 'a' will return 14.


Difference between out and ref type

ref : parameter variable need to be assigned before passing to called function otherwise you will get the compile time error/there is no compulsion for called function to assign value in ref type parameter variable.

out : parameter variable need not to be assigned before passing in the called function but here we have compulsion for called method to assign a value in out type parameter variable before control leaves the current method as compile time error comes.



ParseExact

Case #1
string dateString = "Mon 16 Jun 8:30 AM 2008";
System.DateTime dt = DateTime.Parse(dateString).ToString("dd-MMM-yyyy")

MSDN : Because the Parse (String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results If a specific date and time format will be parsed across different locales, use the DateTime.Parse(String, IFormatProvider) method or one of the overloads of the ParseExact method and provide a format specifier.


Exception : when you try to run this code it will give you an exception "String was not recognized as a valid DateTime".


Case #2
string dateString = "Mon 16 Jun 8:30 AM 2008"; 
string dateformat = "ddd dd MMM h:mm tt yyyy";

Response.Write(DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture).ToString("dd-MMM-yyyy"));

Output : The CultureInfo.InvariantCulture property is used if you are formatting or parsing a string that should be parse able by a piece of software independent of the user's local settings.



TryParseExact

Case #1
string dateString = "Mon 16 Jun 8:30 AM 2008";
string dateformat = "ddd dd MMM h:mm tt yyyy";

DateTime dt;

if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
  Response.Write("After Parsed : " + dt.ToString("dd-MMM-yyyy"));
else
  Response.Write("Parsing Failed:" + dt.ToString("dd-MMM-yyyy"));

Output : Would be "After Parsed : " + , because your target date is exactly matched the format that you mentioned.


Case #2:
string dateString = "Mon 16 Jun 8:30 AM 2008";
string dateformat = "dd ddd MMM h:mm tt yyyy";

if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
  Response.Write("After Parsed : " + dt.ToString("dd-MMM-yyyy"));
else
  Response.Write("Parsing Failed:" + dt.ToString("dd-MMM-yyyy"));

Output : Would be "Parsing Failed : 01-Jan-0001", because your target date is not exactly matched as the format that you mentioned.

Difference between String and string

String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-known by C# programmers.

Disabling Automatic Validation on Save Changes Method

using (var context = new DBContext())
{
    context.Configuration.ValidateOnSaveEnabled = false;
    context.SaveChanges();
}

Distinct in LINQ based on only one field

table.GroupBy(x => x.Column).Select(x => x.FirstOrDefault());

Do Proper Exception Handling

Do

catch(Exception ex) { 
  Logger.GetException(ex.Message); 
}

or

catch(Exception ex) { 
  throw; 
}


Don't

try { } 
catch(Eexception ex) { 
  throw ex; 
}

Dynamic Query for Filtering Data (LINQ-like Query)

Suppose you have a List<Person> and want to filter it dynamically by a property name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 25 },
            new Person { Name = "Bob", Age = 30 },
            new Person { Name = "Charlie", Age = 35 }
        };

        string propertyName = "Age";
        int value = 30;

        var parameter = Expression.Parameter(typeof(Person), "x");
        var property = Expression.Property(parameter, propertyName);
        var constant = Expression.Constant(value);
        var condition = Expression.GreaterThan(property, constant);

        var lambda = Expression.Lambda<Func<Person, bool>>(condition, parameter);

        var filteredList = people.AsQueryable().Where(lambda).ToList();

        foreach (var person in filteredList)
        {
            Console.WriteLine($"{person.Name}, {person.Age}");
        }
    }
}

Dynamic Query with Multiple Conditions

This example dynamically creates a query with AND or OR conditions based on user input.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 25 },
            new Person { Name = "Bob", Age = 30 },
            new Person { Name = "Charlie", Age = 35 }
        };

        var parameter = Expression.Parameter(typeof(Person), "x");

        // Dynamic conditions
        var ageProperty = Expression.Property(parameter, "Age");
        var constant1 = Expression.Constant(30);
        var greaterThan = Expression.GreaterThan(ageProperty, constant1);

        var nameProperty = Expression.Property(parameter, "Name");
        var constant2 = Expression.Constant("Charlie");
        var equal = Expression.Equal(nameProperty, constant2);

        // Combine with OR: (x.Age > 30) || (x.Name == "Charlie")
        var orExpression = Expression.OrElse(greaterThan, equal);

        var lambda = Expression.Lambda<Func<Person, bool>>(orExpression, parameter);

        var result = people.AsQueryable().Where(lambda).ToList();

        foreach (var person in result)
        {
            Console.WriteLine($"{person.Name}, {person.Age}");
        }
    }
}

Dynamic Sorting (OrderBy)

Dynamically create an OrderBy clause for sorting by a property name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 25 },
            new Person { Name = "Bob", Age = 30 },
            new Person { Name = "Charlie", Age = 35 }
        };

        string sortBy = "Age";

        var parameter = Expression.Parameter(typeof(Person), "x");
        var property = Expression.Property(parameter, sortBy);

        var lambda = Expression.Lambda(property, parameter);

        var sortedList = people.AsQueryable()
                               .OrderBy((dynamic)lambda)
                               .ToList();

        foreach (var person in sortedList)
        {
            Console.WriteLine($"{person.Name}, {person.Age}");
        }
    }
}

EF Core: Easily detect slow running queries, and modify hard deletes

Implementing a Performance Interceptor

using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Diagnostics;

public class PerformanceInterceptor : DbCommandInterceptor
{
    private const long QuerySlowThreshold = 100; // milliseconds

    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command, 
        CommandEventData eventData, 
        InterceptionResult<DbDataReader> result)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();

        var originalResult = base.ReaderExecuting(command, eventData, result);

        stopwatch.Stop();
        if (stopwatch.ElapsedMilliseconds > QuerySlowThreshold)
        {
            Console.WriteLine($"Slow Query Detected: {command.CommandText}");
        }

        return originalResult;
    }
}


Implementing Soft Deletes

public class MyEntity
{
    public Guid Id { get; set; }
    public bool IsDeleted { get; set; }
    // Other properties...
}

public class SoftDeleteInterceptor : SaveChangesInterceptor
{
    public override InterceptionResult<int> SavingChanges(
        DbContextEventData eventData, 
        InterceptionResult<int> result)
    {
        foreach (var entry in eventData.Context.ChangeTracker.Entries())
        {
            if (entry.State == EntityState.Deleted && entry.Entity is MyEntity entity)
            {
                entity.IsDeleted = true;
                entry.State = EntityState.Modified;
            }
        }

        return base.SavingChanges(eventData, result);
    }
}


Register the interceptor with your DbContext.

using Microsoft.EntityFrameworkCore;

public class SampleDbContext : DbContext
{
    public DbSet<MyEntity> SampleEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Your_Connection_String");

        // Registering the PerformanceInterceptor
        optionsBuilder.AddInterceptors(new PerformanceInterceptor());

        // Registering the SoftDeleteInterceptor
        optionsBuilder.AddInterceptors(new SoftDeleteInterceptor());
    }   
}

Efficient Distinct Comparisons Using DistinctBy()

DistinctBy() efficiently removes duplicates from a collection based on a specific property without the overhead of GroupBy(). This improves performance and simplifies the code.


using System;
var titles = new List<string> { "Apple", "Banana", "Apple", "Orange", "Banana" };

// Remove duplicates based on value
var distinctTitles = titles.DistinctBy(title => title).ToList();

// Output distinct titles
distinctTitles.ForEach(Console.WriteLine);
//Apple, Banana, Orange