Monday, March 4, 2013

Assigning Null Values to Struct !!!

Well, as we all know that struct are Value Type and hence cannot contain null value. Similar kind of scenario was encountered while developing custom application where a function must return struct, if found in hash table else return null.


After googling, I came across the solution of using Nullable Types.

Sample code is given below :

    public struct ModuleDetails
  {
      public string ModuleName { get; set; }
      public int Module { get; set; }
  } 


public ModuleDetails? GetUserControl(string ModuleName)
{
    try
    {
       if (moduleDictionary.ContainsKey(ModuleName))
       {
          Assembly assem = Assembly.GetExecutingAssembly();
          ModuleDetails details = moduleDictionary[ModuleName];
          Type t = assem.GetType(details.ModuleName);
          ModuleDetails moduleDetails = (ModuleDetails)Activator.CreateInstance(t);

          if (string.IsNullOrEmpty(moduleDetails.ModuleName))
          {
              throw new Exception("Unable to create module instance for Module : " + ModuleName);
          }
          return moduleDetails;
       }
       else
       {
          return null;
       }
    }
    catch (Exception ex)
    {
        return null;
    }
 }

No comments:

Post a Comment