Code #1: Reverse An Array

How to reverse an array (in C#) without using Array.Reverse() method?

int[] arr = {1,3,4,9,8};
for (int i = 0; i < arr.Length / 2; i++)
{
int tmp = arr[i];
arr[i] = arr[arr.Length - i - 1];
arr[arr.Length - i - 1] = tmp;
}
Console.WriteLine(string.Join(",", arr));

C# – Stack-overflow Exception

Stack-overflow Exception

The exception is triggered because of too many nested method calls. Each method call is kept on the stack memory. The program terminates because of infinite and uncontrolled recursion. Process terminated message is displayed with no recovery option also try-catch block will not be able to catch the exception.

One of the common place the exception happens is when setting the get and set methods in a class and forgetting to set the backing field. This happens because you are recursively calling the property again which creates infinite recursion at run time. This class will compile successfully but will throw exception during run time.
Example:

public class Data
  {
        public string MemberId { 
            get {return this._ID;}
            set { this._ID = value;}
        } 

        public string ALT_MEM { get; set; } 
  }

To solve this you will need to declare private backing field to hold the value.

Example:

public class Data
  {
        //You need to declare this to avoid stackoverflow exception
        private string _ID;

        public string MemberId { 
            get {return this._ID;}
            set { this._ID = value;}
        } 

        public string ALT_MEMBNO { get; set; } 


  }

If you are using the auto-property feature, it will create a hidden backing field so you don’t need to worry about it.

  
public string FirstName { get; set;}

Live as if you were to die tomorrow. Learn as if you were to live forever..
-Mahatma Gandhi

C# Error: Sequence contains no element

C# Error: Sequence contains no element

This error happen when I was trying to call Single() command like this:
Held holdData = new HeldBusinessLogic().Get(id: cId).Single();

Since there was no record in the Held table, the Single() command results in error: “Sequence contains no elements”

To fix the issue I had to change the code to:
Held holdData = new HeldBusinessLogic().Get(id: cId).FirstOrDefault();

The FirstOrDefault() returns null when there is no record whereas Single() tries to retrieve an element from the sequence

This error can also result when you attempt to execute any aggregate method on an empty result set.

Example
int maxData = context.Surface.Max(s => s.Surface.GetValueOrDefault());

To fix this:
int maxData = context.Surface==null?0: context.Surface.Max(s => s.Surface.GetValueOrDefault());

Another Filter example

Error
claim.Held.First(c => c.ClaimId == claimId);
Solution
claim.Held.FirstOrDefault(c => c.ClaimId == claimId);

However this can happen with the following commands also:
First() – use first when you know the sequence will have at least one element
FirstAsync() – Asynchronously returns the first element of a sequence.
SingleAsync() – Asynchronously returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
Last() – Returns the last element of a sequence.
LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.
LastAsync()

C# Version History

C# Version History

Version Features Visual Studio Framework
C# 7.2 Reference semantics with value types
Non-trailing named arguments
Leading underscores in numeric literals
private protected access modifier
Visual Studio 2017 version 15.5 .NET Core/ .NET Framework 4.7.1
C# 7.1 async Main method
default literal expressions
Inferred tuple element names
Visual Studio 2017 version 15.3 .NET Framework 4.7
C# 7.0 out variables
Tuples
Discards
Pattern Matching
ref locals and returns
Local Functions
More expression-bodied members
throw Expressions
Generalized async return types
Numeric literal syntax improvements
Visual Studio 2017 .NET Framework 4.7
C# 6.0 Read-only Auto-properties
Auto-Property Initializers
Expression-bodied function members
using static
Null – conditional operators
String Interpolation
Exception filters
nameof Expressions
await in catch and finally blocks
index initializers
Extension methods for collection initializers
Improved overload resolution
Visual Studio 2015 .NET Framework 4.6
C# 5.0 Async / await, and caller information attributes. Visual Studio 2012 .NET Framework 4.5
C# 4.0 Dynamic binding
Optional parameters and named arguments
Type variance with generic interfaces and delegates
Generic co- and contravariance
Embedded interop types
Visual Studio 2010 .NET Framework 4.0
C# 3.0 LINQ
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expressions
Expression trees
Partial Methods
Visual Studio 2008 .NET Framework 3.0\3.5
C# 2.0 Generics
Partial types
Anonymous methods
Iterators
Nullable types
Private setters (properties)
Method group conversions (delegates)
Covariance and Contra-variance
Static classes
Visual Studio 2005 .NET Framework 2.0
C# 1.1 #line pragma and xml doc comments. Visual Studio 2003 .NET Framework 1.0/1.1
C# 1.0 First initial release Visual Studio 2002 .NET Framework 1.0/1.1

C# Difference between ref and out parameters

In C# by default the parameters are always passed by value but you can also use out and ref keywords for passing parameters by reference.
Both keywords are identical with the only difference of initializing the value of the variable. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn’t differentiates between the two while it created IL for ref and out).

Sample Code

using System;
namespace HelloWorld
{
 class Hello 
 {
 static void Main() 
 {
     Console.WriteLine("**********Using Ref Method**********");     
     int num = 10;
     MyMethodRef(ref num);
     Console.WriteLine("Value Outer Method : {0}", num);
     
     Console.WriteLine("**********Using Out Method**********");
     int numout = 10;
     MyMethodOut(out num);
     Console.WriteLine("Value Outer Method : {0}", numout);
 }

 private static void MyMethodRef(ref int number){
    number += 20;
    Console.WriteLine("Value Inner Method : {0}", number);
 }
 
 private static void MyMethodOut(out int number)
 {
    number = 20;
    Console.WriteLine("Value Inner Method : {0}", number);
 }
 }
}

Output
**********Using Ref Method**********
Value Inner Method : 30
Value Outer Method : 30
**********Using Out Method**********
Value Inner Method : 20
Value Outer Method : 10

Using Ref
With Ref keyword, the objects is initialized first before used in the function, you need to set the value first then call in the method to read and modify. If you tried to pass num variable without initializing to the MyMethodRef() method, you’d end up with a compilation error: Use of unassigned variable ‘num‘.

Using Out
With Out keyword, the variable have to be assigned inside the function. A variable passed in using out cannot be read from before its assigned to.
The method must be set it before returning.

You can use out and ref parameters for overloading methods.
static void Method(String name){}
static void Method(ref String name){} //ok
static void Method(out String name){} //error

You can overload the standard method by using the ref or out keywords but cannot overload that differs only by out and ref simultaneously. The parameter’s type must match the type of the value that is passed.

C# List of String Functions

String Functions

string.IsNullOrEmpty()read more here

Code Sample:

string output = string.IsNullOrEmpty(someString) ? "0" : someString; 
 You can also use the null coalescing operator (??), but it would not handle empty strings. 
 string output = somePossiblyNullString ?? "0";

string.sNullOrWhiteSpace() – Indicates whether a specified string is null, empty, or consists only of white-space characters.

string.Empty – declare a empty string

string.ToUpper() – covert the string to uppercase

string.Split() – extracts sub-string in string