Tuesday, 5 January 2016

Whats new in c# 6.0,5.0,4.5


A. What is new in c#6.0.

1. Null-Conditional Operator
example :
      public static string Truncate(string value, int length)
      {          
          return value?.Substring(0, Math.Min(value.Length, length));
      }
     public void Truncate_WithNull_ReturnsNull()
     {
       Assert.AreEqual<string>(null, Truncate(null, 42));
     }

2. Primary Constructor:
   primary constructors will help destroy the pain of capturing values of constructor parameters to fields in the class for further operations. This is really useful. The main purpose for it is using constructor parameters for initialization. When declaring a primary constructor all other constructors must call the primary constructor using :this().


class Person(string firstName, string lastName)
{
    public string FirstName { get; set; } = firstName;
    public string LastName  { get; } = lastName;

}

3. Auto-Property Initializers

   In C# 6 and later, you can initialize auto-implemented properties similarly to fields:
    eg. public string FirstName { get; set; } = "Jane";






B. What is new in c#5.0.



  C# 5.0  was released on August 15, 2012 .
 1.  Async Programming.
C# 5.0 Async feature introduces two keywords async and await which allows you to write asynchronous code more easily and intuitively like as synchronous code. Before C# 5.0, for writing an asynchronous code, you need to define callbacks (also known as continuations) to capture what happens after an asynchronous process finishes. This makes your code and other routine task such exception handling complicated.
Both the keywords are used in a combination of each other. Hence, an await operator is applied to a one or more than one expressions of an async method. An async method returns a Task or Task<TResult> that represents the ongoing work of the method. The task contains information that the caller of the asynchronous method can use, such as the status of the task, its unique ID, and the method's result.
2.  Caller Information.

Caller Information can help you in tracing, debugging and creating diagnose tools. It will help you to avoid duplicate codes which are generally invoked in many methods for same purpose, such as logging and tracing.
You can get the following information of caller methods
1.               CallerFilePathAttribute
            Full path of the source file that contains the caller. This is the file path at compile time.
2.               CallerLineNumberAttribute
           Line number in the source file at which the method is called.
3.               CallerMemberNameAttribute
           Method or property name of the caller.

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Main method Start");
            MyMethodB();
            MyMethodA();
            Console.WriteLine("Main method End!");
            Console.ReadLine();
        }

        static void MyMethodA()
        {
            MyMethodB();
        }
        static void MyMethodB([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
        {
            InsertLog(memberName+"Line no:"+sourceLineNumber.ToString()+" file path:"+sourceFilePath.ToString());
        }
        static void InsertLog(string method)
        {
            Console.WriteLine("{0} called MyMethodB at {1}", method, DateTime.Now);
        }
    }
}

3. C# Evolution Matrix

Best practice code

All questions list

Problem 1: sort the given array
                    Input--> [-8, -5, -3, -1, 3, 6, 9] 
                    Output-->[1,3,3,5,6,8,9]
Solution:
Private int[] SortedArray()
{
        int[] a = { -8, -5, -3, -1, 3, 6, 9 };
            for (int i = 0; i < a.Length; i++)
            {
             
                for (int j = i; j < a.Length; j++)
                {
                    int x = Convert.ToInt32(a[i]);
                    if (x < 0)
                    {
                        x = x * (-1);
                    }
                    int y = Convert.ToInt32(a[j]);
                    if (y < 0)
                    {
                        y = y * -1;
                    }
                    if (x > y)
                    {
                        int temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                        x=a[i];
                    }
                }
            }
            return a;
}
----------------------------------------------------------------------------------------------------------------------

2. Given an array A of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of A.

static void Main(string[] args)
        {
            Program p = new Program();
            int[] arr = { 11, -12, 15, -3, 8, -9, 1, 8, 10, -2 };
            int answer = p.maxSum(arr, 10);//answer should be 30
        }
        int maxSum(int[] a, int n)
        {
            int i, j, k;
            int sum, maxSum = 0;
            for (i = 0; i < n; i++)
            {
                for (j = i; j < n; j++)
                {
                    sum = 0;
                    for (k = i; k < j; k++)
                    {
                        sum = sum + a[k];
                    }
                    if (sum > maxSum)
                        maxSum = sum;
                }
            }
            return maxSum;

        }

 OR

static void Main(string[] args)
        {
            Program p = new Program();
            int[] arr = { 11, -12, 15, -3, 8, -9, 1, 8, 10, -2 };
            int answer = p.maxSum(arr, 10);
        }
        int maxSum(int[] a, int n)
        {
            int i, j, sum, maxSum;
            maxSum = 0;
            for (i = 0; i < n; i++)
            {
                sum = 0;
                for (j = i; j < n; j++)
                {
                    sum = sum + a[j];
                    if (sum > maxSum)
                        maxSum = sum;
                }
            }
            return maxSum;

        }
-----------------------------------------------------------------------------------------------------------------------

What is CCW (COM Callable Wrapper)

When a COM client calls a .NET object, the common language runtime creates the managed object and a COM callable wrapper (CCW) for the object. Unable to reference a .NET object directly, COM clients use the CCW as a proxy for the managed object. 

The runtime creates exactly one CCW for a managed object, regardless of the number of COM clients requesting its services. As the following illustration shows, multiple COM clients can hold a reference to the CCW that exposes theINew interface. The CCW, in turn, holds a single reference to the managed object that implements the interface and is garbage collected. Both COM and .NET clients can make requests on the same managed object simultaneously.

COM callable wrapper


What is RCW (Runtime Callable Wrapper)

***The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object.

RCW

The runtime creates exactly one RCW for each COM object, regardless of the number of references that exist on that object. The runtime maintains a single RCW per process for each object. If you create an RCW in one application domain or apartment, and then pass a reference to another application domain or apartment, a proxy to the first object will be used. As the following illustration shows, any number of managed clients can hold a reference to the COM objects that expose INew and INewer interfaces.
RCW
***Using metadata derived from a type library, the runtime creates both the COM object being called and a wrapper for that object. Each RCW maintains a cache of interface pointers on the COM object it wraps and releases its reference on the COM object when the RCW is no longer needed. The runtime performs garbage collection on the RCW.

***Specifically, the RCW provides marshaling for method arguments and method return values whenever the client and server have different representations of the data passed between them.


***The standard wrapper enforces built-in marshaling rules. For example, when a .NET client passes a String type as part of an argument to an unmanaged object, the wrapper converts the string to a BSTR type. Should the COM object return a BSTR to its managed caller, the caller receives a String. Both the client and the server send and receive data that is familiar to them. Other types require no conversion. For instance, a standard wrapper will always pass a 4-byte integer between managed and unmanaged code without converting the type.

Saturday, 2 January 2016

What is property and Indexer in c#

  1. By Property we can evaluate the characteristics of any objects. 
  2. A property and function in c# is a wrapper meant for variables and elements, i.e it is an encapsulate entity.
  3.  A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field
  4. Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
  5. Bynproperty we can implement the validations.
  6. property used to implement the a business logic.
  7. A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. 
  8. The value keyword is used to define the value being assigned by the set accessor.
  9. Properties that do not implement a set accessor are read only.
  10. C# supports static properties.
  11. C# supports abstract properties

Auto implemented property:

1. auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.

2. In C# 6 and later, you can initialize auto-implemented properties similarly to fields:
    eg. public string FirstName { get; set; } = "Jane";


Indexer:


An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array.

using System;/// <summary>
///
     A simple indexer example./// </summary>class IntIndexer
{
    private string[] myData;    public IntIndexer(int size)
    {
        myData = 
new string[size];        for (int i=0; i < size; i++)
        {
            myData[i] = "empty";
        }
    }

    public
 string this[int pos]
    {
        get
       {            return myData[pos];
        }
        set
       {
            myData[pos] = 
value;
        }
    }

    static
 void Main(string[] args)
    {
        int size = 10;

        IntIndexer myInd = 
new IntIndexer(size);

        myInd[9] = "Some Value";
        myInd[3] = "Another Value";
        myInd[5] = "Any Value";

        Console.WriteLine("\nIndexer Output\n");

        for
 (int i=0; i < size; i++)
        {
            Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
        }
    }
}


Overloaded Indexers:
using System;/// <summary>
///
     Implements overloaded indexers./// </summary>class OvrIndexer
{
    private string[] myData;    private int         arrSize;    public OvrIndexer(int size)
    {
        arrSize = size;
        myData = 
new string[size];        for (int i=0; i < size; i++)
        {
            myData[i] = "empty";
        }
    }

    public
 string this[int pos]
    {
        get
       {            return myData[pos];
        }
        set
       {
            myData[pos] = 
value;
        }
    }

    public
 string this[string data]
    {
        get
       {            int count = 0;
            for
 (int i=0; i < arrSize; i++)
            {
                if (myData[i] == data)
                {
                    count++;
                }
            }
            return count.ToString();
        }
        set
       {            for (int i=0; i < arrSize; i++)
            {
                if (myData[i] == data)
                {
                    myData[i] = 
value;
                }
            }
        }
    }

    static
 void Main(string[] args)
    {
        int size = 10;
        OvrIndexer myInd = 
new OvrIndexer(size);

        myInd[9] = "Some Value";
        myInd[3] = "Another Value";
        myInd[5] = "Any Value";

        myInd["empty"] = "no value";

        Console.WriteLine("\nIndexer Output\n");

        for
 (int i=0; i < size; i++)
        {
            Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
        }

        Console.WriteLine("\nNumber of \"no value\" entries: {0}", myInd["no value"]);
    }
}






Diff. b/w Properties and Indexer:



Property
Indexer
Allows methods to be called as if they were public data members.
Allows elements of an internal collection of an object to be accessed by using array notation on the object itself.
Accessed through a simple name.
Accessed through an index.
Can be a static or an instance member.
Must be an instance member.
A get accessor of a property has no parameters.
A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of a property contains the implicit valueparameter.
A set accessor of an indexer has the same formal parameter list as the indexer, and also to the value parameter.
Supports shortened syntax with Auto-Implemented Properties (C# Programming Guide).
Does not support shortened syntax.














Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft