Dynamic in C# 4.0

Dynamic type is introduced C# 4.0. As its name specifies type of the defined variable is decided dynamically at runtime. At compile time the variable that is declared as dynamic is assumed to be support any type or operation. As it does everything at runtime if code is not valid then errors are caught at runtime. Two major disadvantages of dynamic type are No compile time checking and No intelliSense support

Dynamic type example

Suppose we have class called SomeClass that have methods Method1() and Sum(intx, int y).
    public class SomeClass
    {
        public SomeClass()
        {
        }

        public void Method1()
        {
            //Do something
        }

        public int Sum(int x, int y)
        {
            return x + y;
        }
    }

and we are now trying to use the above class using dynamic type.
    public partial class DynamicType : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            dynamic someclass_dy = new SomeClass();
           
            someclass_dy.Method1();

            someclass_dy.Sum(10, 3);

            someclass_dy.SomeOtherMethod();
        }
     }

In above code we have defined dynamic type object of class SomeClass(). and now if you try to access methods from that class it will not show any method in intelliSense, you explicitly need to know the class methods and call them that is because dynamic type does not supports compile time checking. If you notice there is code line someclass_dy.SomeOtherMethod(); where SomeOtherMethod() does not exists in SomeClass() still it will not throw any compile time error, but it will throw runtime error.


Tuple in C# 4.0

Tuple is a new class introduced in C# 4.0. Tuple basically provides way to group the items of different data types. A static Tuple class provides 8 overloads of create method to create Tuple of size 1 to 8. Also using new keyword and nesting tuples you can create more sized Tuple. Now for example tuple created with 3 elements called 3-tuple or triple that can hold three elements of any type. So first element may be firstname that is string, second element may be phone number that is int and salary which is double may be the third element. And we can read those values using item property of tuple like for 3-tuple it will tuple.Item1, tuple.Item2 and tuple.Item3.

Tuple example 3-tuple

     var tuple3 = new Tuple("Johan", 1234567890, 56000.90);
     Console.WriteLine(tuple3.Item1);
     Console.WriteLine(tuple3.Item2);
     Console.WriteLine(tuple3.Item3);

In above example it will print
Output:
  Johan
  1234567890
  56000.90

Lazy loading C#. Lazy initialization.

C# 4.0 introduced new class Lazy which provided for Lazy initialization. Lazy instantiation here means object is not created until it is get used first time. Primary use of Lazy initialization is performance improvements, reduce program memory requirements.Lazy provides thread safe object initialization.

Lasy<T> example to load object lazily

public partial class LazyClass : System.Web.UI.Page 
{
 private Lazy<List<string>> lazyItems = null; 
 public LazyClass() 
 { 
   lazyItems = new Lazy<List<string>>(GetItems); 
 } 
 public List<string> GetItems() 
 {
      List<string> items = new List<string>(); 
      for (int i = 0; i < 10; i++) 
       { 
          items.Add(string.Format("Item {0}", i)); 
       } return items;
 }

 public List<string> GetItemValues { get { return lazyItems.Value; } } 
}

So in above example we have defined private Lazy<List<string>> lazyItems = null; and then in constructor we have delegate the call to GetItems method which will return list of items. But here it will not generate and return list until we call "lazyItems.Value".


Skip in Linq C#

Skip() in Linq avoids or skips the given number of elements from the sequence.

Skip() example in Linq

  protected void Page_Load(object sender, EventArgs e)
        {
            var numArr = new int[5];
            numArr[0] = 9;
            numArr[1] = 6;
            numArr[2] = 3;
            numArr[3] = 5;
            numArr[4] = 2;

            var numbers = numArr.Skip(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
// Output will be 5, 2

So in above example of skip in linq, we have numArr.Skip(3);, that will skip first three elements from array and print remaining array elements.

Take() in Linq C#

In Linq i.e. System.Linq, Take operator is used to get the first specified number of elements a sequence.

Linq Take() example

using System.Linq;
protected void Page_Load(object sender, EventArgs e)
        {
            var numArray = new int[5];
            numArray[0] = 95;
            numArray[1] = 66;
            numArray[2] = 3;
            numArray[3] = 54;
            numArray[4] = 2;


            var numbers = numArray.Take(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
        }
//It will print 95, 66, 3.

So in above sample code of Take() we have numArray.Take(3) that means it will return us the sequence of first three elements from array.

AsEnumerable() in Linq

AsEnumerable() method in Linq is used to cast or convert given type into it's IEnumerable type. AsEnumerable() basically changes the compile time type of given type that implements IEnumerable to IEnumerable itself.

Sample code to use AsEnumerable() in Linq

 protected void Page_Load(object sender, EventArgs e)
  {
      var numArray = new int[5];
      numArray[0] = 5;
      numArray[1] = 10;
      numArray[2] = 7;
      numArray[3] = 9;
      numArray[4] = 1;

      var numbers = numArray.AsEnumerable();
      foreach (var number in numbers)
       {
          Console.WriteLine(number);
       }
  }

Convert ToList() in Linq

In C# Linq, there is .ToList() extension method that is used to convert IEnumerable to List of type. Like .ToArray(), ToList() also forces immediate query execution and stores query result in List.

Example that shows how to convert array to list

 protected void Page_Load(object sender, EventArgs e)
  {
     string[] language = { "C#", "C++", "Java", "Pascal", "Cobol" };
     List languageList = language.ToList();

     foreach (string lang in languageList)
     {
                Console.WriteLine(lang);
     }
  }

Convert ToArray in linq

In C# while using Linq, we have .ToArray() extension method that is used to convert IEnumerable to an array. .ToArray() forces immediate query execution and stores query result in an array.

Example of Linq .ToArray()

 public partial class LinqToArray : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            var carslist =
                new List 
                        { new Cars { Company = "Maruti Suzuki", Average = 15.2 },
                          new Cars { Company = "Mercedes", Average = 18.7 },
                          new Cars { Company = "Volvo", Average = 20.0 },
                          new Cars { Company = "Hundai", Average = 12.8 } };

            var companies = carslist.Where(c => c.Average > 15)
                                         .Select(c => c.Company)
                                         .ToArray();

            foreach (var company in companies)
            {
                Console.WriteLine(company);
            }
        }

    public class Cars
    {
        public string Company { get; set; }
        public double Average { get; set; }
    }

Output:
   /*
     //Maruti Suzuki
     // Mercedes
     // Volvo
   */

In above sample code we have converted List to array using linq.

ASP.NET CompareValidator

In this post we will see how to use compare validator to compare the two input values. Using compare validator we can compare two values from two different input controls or we can compare input value with some constant or fixed value.

Example of compare validator

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul style="list-style-type: none">
            <li>
                <asp:TextBox ID="txt1" runat="server" />
                =
                <asp:TextBox ID="txt2" runat="server" />
            </li>
            <li>
                <asp:Button ID="Button1" Text="Validate" runat="server" />
            </li>
        </ul>
        <br>
        <asp:CompareValidator ID="compareval" Display="dynamic" ControlToValidate="txt1"
            ControlToCompare="txt2" ForeColor="red" Type="String" EnableClientScript="false"
            Text="Values are not equal." runat="server" />
    </div>
    </form>
</body>
</html>

So in compare validator we need to set ControlToValidate and ControlToCompare in order to compare two input values.

RangeValidator to validate data in between | asp.net

From the set of validation server controlin asp.net we will see how to use RangeValidator in this post.

RangeValidator is used to check if values entered are in between specific range or not. In order to use RangeValidator, we need to add server control on web form.

RangeValidator example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter a number between 0 and 5:
        <br>
        <asp:TextBox ID="txtNumber" runat="server" />
        <asp:RangeValidator ID="RangeValidator1" ControlToValidate="txtNumber" MinimumValue="0"
            MaximumValue="5" Type="Integer" Text="The number should be in between 0 to 5."
            ForeColor="red" runat="server" />
        <br>
        <asp:Button ID="Button1" Text="Submit" runat="server" />
    </div>
    </form>
</body>
</html>

In order to rangevalidator to be work we need to set few properties: 1. Minimum value
2. Maximum value
3. Control to validate
4. Type of data i.e. Interger, Date...etc.
5. And the Text for error message