Sunday, November 16, 2008

Control State, Partial Class, Iterators, Nullable – At a glance

Control State, Partial Class, Iterators, Nullable – At a glance

Control State



Control State is a new feature added in Asp.net2.0 framework. Control state is very similar to View State, where value is stored in the hidden_VIEWSTATE form field, with a little difference i.e. Control State cannot be disabled. Control state is intended to be used only for storing crucial information across postbacks.


Partial Classes



Partial Classes are new feature added to the .net framework 2.0. Partial classes allow dividing up a single class into multiple class file. These classes are combined into a single class later when compiling. To create a partial class there is a simple keyword partial.

Example:

public partial class MathClass
{
public int Add(int a, int b)
{
return a+b;
}
}

public partial class MathClass
{
public int Substract(int a, int b)
{
return a-b;
}
}



At compile time system gather the information of all relevant partial classes MathClass in above case, and combined all into a single class.

Iterators


Iterators enable us to use foreach loops on our own custom types. To achieve the same we need to have class implement the IEnumerable interface.

Example:

public class mylistClass
{
internal object[] objElements;
internal int intcount;
public IEnumerator GetEnumerator()
{
yield return “Gaurav”;
yield return “Shuby”;
}
}

//here is the use
//put following code at anywhere as per your requirement, I used it on page_load

Void pageload(object sender, EventArgs e)
{
//create an instance of class
mylistClass custList = new mylistClass();

foreach (String custItem in custList)
{
Response.Write(“Item : “ +custItem.ToString() + “<br/>”);
}

}



Note:
You need to include System.Collections namespace in above.


Nullable



Nullable types are instances if System.Nullable. A nullable type can represent the normal range of values of its underlying value type plus an additional null value.

Example:


namespace AStepAhead.Nullable
{
class nullableclass
{
static void Main(string[] args)
{
int? num = null;
int? num1 = null;
if (num.HasValue == true)
{
Console.WriteLine("Num : {0}", num);
}
else
{
Console.WriteLine("Num has Null value");
}

//int y = num.GetValueOrDefault(); //throw an exception
int z;
try
{
//y = num.Value;
//Console.WriteLine("Y:{0}", y);
z = num1 ?? 2;
Console.WriteLine("Z:{0}", z);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}


Console.ReadLine();
}
}
}


Note:
You need to include System.Collections.Generic namespace in above.

No comments:

Post a Comment