Unveiled the features of C#


Hello Fellow developers!

This article describes some tricks about popular contest questions.

1. Write a program to print current Source code line number in c#:
 public static void Main(string[] args)
 {
     Console.WriteLine("Hello World, from line {0}!", GetLineNumber());
     Console.ReadLine();
 }
private static int GetLineNumber([CallerLineNumber] int sourceLineNumber = 0)
{
    return sourceLineNumber;
}
You need to use System.Runtime.CompilerServices for "CallerLineNumber" attributes which Allows you to obtain the line number in the source file at which the method is called. Simply easy. isn't it? There are other attributes like [CallerMemberName] - which obtains the method name from which it was called, [CallerFilePath]- returns the source file path.

 2. Now next puzzle, is a popular equation "2+2 = 5". so how to do it in C#?. It also pretty simple. believe me!

public static void Main(string[] args)
{
        var result = Enumerable.Range(2, 2).Sum();
        Console.WriteLine(" 2 + 2 = {0}", result);
        Console.ReadLine();
}

 3. Applying an arithmetic operators on two lists in c#.
public static void Main(string[] args)
{
    var listA = new List() { 2, 2, 3 };
    var listB = new List() { 5, 1, 8 };
    var result = listA.Zip(listB, (x, y) => x * y);
    foreach (var r in result)
    {
         Console.WriteLine(" result {0}", r);
    }

    Console.ReadLine();
}

Here, the Zip extension method do all the tricks. It applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

Hope this helps you to know some unveiled features of c#.
Have a happy coding!

Comments

Popular posts from this blog

Fetching Address book AKA Contact information from Device using Xamarin.Forms

Hyperlink label in Xamarin.Forms

Custom Attributes in MVC