RSS

Generics and Nullables in C# 2.0

Generics in C# 2.0
1. The Generics was added to C# 2.0 to remove the need for casting, improve type safety, reduce the amount of boxing required, and to make it easier to create generalized classes and methods.
2. Generic classes and methods accept type parameters, which specify the type of objects that they operate on.
3. Version 2.0 of the .NET Framework Class Library includes generic versions of many of the collection classes and interfaces in the System.Collections.Generic namespace
EX:

using System.Collections.Generic;
...
Queue myQueue = new Queue();
Circle myCircle = new Circle();
myQueue.Enqueue(myCircle);
...
myCircle = myQueue.Dequeue();


NOTE:
• The use of the type parameter between the angle brackets, , when
declaring the myQueue variable.
• The lack of a cast when executing the Dequeue method.
* The compiler will check to ensure that types are not accidentally mixed,
generating an error at compile time rather than runtime if you try to
dequeue an item from circleQueue into a Some other object.
- The bellow class explains the Generic with Delegate of Type T

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public delegate void dele1(T x);

class Class1
{
public void fn1(int x)
{
Console.WriteLine(x);
}
public void fn2(string x)
{
Console.WriteLine(x);
}
}
class myclass
{
static void Main(string[] ar)
{
Class1 c = new Class1();
dele1 ob = new dele1(c.fn1);
dele1 ob1 = new dele1(c.fn2);
ob(10);
ob1("stg");
}
}
}

Nullable Types in C# 2.0
We can now assign the null value to value types by defining nullable types. We do this by adding a question mark to the immediate right of the type name when defining a variable. Nullable types derive from the generic type System.Nullable. Instead of defining types from this generic class, We can simply just use T? (where T is the type (class, struct, etc.).

Two properties make nullable types quite useful: HasValue and Value. HasValue evaluates to true if the type is not null, otherwise it's false. Value will return the underlying value, whether it's null or not.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Class3
{
static void Main(string[] a)
{
int? myInt1 = null;

if (myInt1 == null)
Console.WriteLine("myInt1 is null.");
else
Console.WriteLine("myInt1 is Not null.");
// Or, we can check for a value this way:
myInt1 = 1;
if (myInt1.HasValue)
Console.WriteLine("myInt1 has a value = {0}", myInt1.Value);
else
Console.WriteLine("myInt1 is null.");
}
}
}

0 comments:

Post a Comment