Experience the power of Ctrl+C and Ctrl+V..... RSS 2.0
 Wednesday, March 21, 2007

What do you think will be output of the following C# code?

using System;
using System.Collections.Generic;
using System.Text;

namespace TestNull
{
    class Program
    {
        static void Main(string[] args)
        {
            int TestVal;
            TestVal = 1;
            if (TestVal != null)
            {
                // Assign null to an integer type
                TestVal = null;
                Console.WriteLine("TestVal assigned null.");
            }
            else
            {
                Console.WriteLine("TestVal cannot be assigned null.");
                Console.ReadLine();
            } 
        }
    }
}

Stop reading further, if you have guessed that executing the code will result in an error.

Error : Cannot convert null to 'int' because it is a value type at the following line:

TestVal = null;

We cannot assign Null to value type variables. This poses a problem when we want to insert a null DateTime or integer value to a DateTime/int field in the database table.

So in order to get out of this error .Net 2.0 provides a option called Nullable Types.If we want to define integer as a Nullable type the following syntax has to be followed

int? <VariableName>=Value.

In our above C# Code

Replace the declaration of

int TestVal to int? TestVal;

If the Variable TestVal has no value it will be assigned null else it will take the Assigned Value.

If you want to check if the value type has any value, use the HasValue property as shown below.

if (TestVal.HasValue)
{
//...do something
}

Nullable type is constructed from the generic Nullable structure. This can be extended to other data types also for example to DateTime , bool etc.

From MSDN.

Nullable types have the following characteristics:

  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

  • The syntax T? is shorthand for System.Nullable<T>, where T is a value type. The two forms are interchangeable.

  • Assign a value to a nullable type in the same way as for an ordinary value type, for example int? x = 10; or double? d = 4.108;

  • Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();

  • Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;

    • The HasValue property returns true if the variable contains a value, or false if it is null.

    • The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.

    • The default value for a nullable type variable sets HasValue to false. The Value is undefined.

  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

Wednesday, March 21, 2007 3:13:24 PM (India Standard Time, UTC+05:30)  #    Comments [0] - Trackback
CSharp
 Tuesday, March 20, 2007

There are many scenarios where we might want to validate a user against the organization LDAP. There is a difference between an LDAP authentication and an LDAP look up. This example is not about LDAP authentication but about getting information from LDAP.

Imagine that a user is already authenticated using windows authentication and we need to retrieve the user's details like domain name, manager name etc from LDAP. Below is an example where a look up on LDAP is done to retrieve the first name and the last name for a user by passing the ntuserdomainid.

1. Add a reference to the System.DirectoryServices.dll to the application.

protected void Page_Load(object sender, EventArgs e) 

{ 

string domainAndUsername = "asiapacific:*********"; 

string ldapPath = ConfigurationManager.AppSettings["ldapDirectory"].ToString(); 

DirectoryEntry userEntry = new DirectoryEntry(ldapPath); 

try 

{ 

userEntry.AuthenticationType = System.DirectoryServices.AuthenticationTypes.ServerBind; 

if (userEntry != null) 

{ 

DirectorySearcher searcher = new DirectorySearcher(userEntry); 

searcher.Filter = String.Format("(ntuserdomainid={0})", domainAndUsername); 
//Validate against the Domain Id. 

SearchResult result = searcher.FindOne(); 

string FName = result.Properties["givenname"][0].ToString(); //Retrieves the First Name 

string LName = result.Properties["sn"][0].ToString(); //Retrieves the Last Name 

} 

} 

catch (Exception ex) 

{ 

} 

}

 

ntuserdomainid, givenname, sn are some of the properties of the LDAP directory. Looking at the result object in

debug mode will show more properties.

Tuesday, March 20, 2007 4:53:47 PM (India Standard Time, UTC+05:30)  #    Comments [0] - Trackback
asp.net | CSharp
 Friday, March 16, 2007

Initialize();

Print ("Hello World. Welcome to my school of thought");

Close();

Friday, March 16, 2007 4:37:07 PM (India Standard Time, UTC+05:30)  #    Comments [0] - Trackback
dasBlog
Navigation
Statistics
Total Posts: 3
This Year: 0
This Month: 0
This Week: 0
Comments: 0
Sponsored Links
Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Karthik
Sign In
All Content © 2008, Karthik
DasBlog theme 'Business' created by Christoph De Baene (delarou)