5 things I would like to see in C# 5.0

C# 4.0 is out with a lots of new specs this year. Few of them are really good, like the support of Task level Parallelism, Dynamic behavior of objects etc. So C# is very rich now in all respect. But this is not the end of everything. As I did introduced few old but Unknown C# topics, I would also love to explore new things that comes up with C#. So lets discuss a few things which I would love to have.

There is already a buzz around on C# 5.0 specifications in forums. A notable discussion around should be some threads like

What features you want to see in C# 5.0
C# language speculation 4.5 /5.0

etc. These community links are really great where a lots of people voted for new language specs, while quite a few things are already would be in process like :

Binding Operators

Binding Operators may be C# 5.0. The support for Binding on .net objects are awesome. I came to know this from Chris on his post where he speaks how Binding operators looks like long ago. The delphi assignment operator := is now been used in this purpose. :=:  would be used for two way binding.  Thus

comboBox1.Text :=: textBox1.Text; 

means there would be two way binding between the properties so that when ComboBox1.Text changes its Text it will automatically change the value of Textbox1.Text.
Binding is actually not a new thing to the system. In WPF we already have Binding in place, but for that we need the properties to have implemented from INotifyPropertyChanged. So it is not in the language, the WPF objects are doing this internally by handling the PropertyChanged event on the object. But if that is included as an operator it would be a cool feature to add on.

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

WPF Tutorial : Styles, Triggers and Animations : 7


Perhaps the most interesting and most important feature for any WPF application is Styling. Styling means defining styles for controls, and store in reusable ResourceDictionaries and hence forth, it could be used later on by calling its name. Styles in WPF could be well compared with CSS styles. They are both similar in most of the cases, while the former extends the feature allowing most of the features which WPF have. In this article I will discuss mostly how you could use Style in your WPF application to enhance the Rich experience of your UI.


WPF exposes a property Style for every Control. If you look into the object Hierarchy, the Style is basically a property which exposes an object of Style in FrameworkElement. So each object can associate it and define custom setters to manipulate the basic look and feel of a control.

Clearly, the above diagram shows the association of Style in FrameworkElement and from the object hierarchy every control somehow inherits from FrameworkElement and hence style will be available to it. Style is also a WPF object which is inherited form DispatcherObject which helps in setting different properties of your UI Element.

How Style differs from Theme  ?

Before we move further into Styles lets talk about Themes. Theme is totally different from Styles. Themes are defined at OS level, or more precisely a Theme can take part of delivering styles all over the Desktop while Styles are restricted to the contextual area of a WPF window. WPF are capable of retrieving the color scheme which is defined in OS level. Say for instance, if you do not define style for your application, the elements in the screen will automatically get styles from external environment. Say for instance, in XP if you change the theme to something else you would see that the buttons, TextBox on your WPF window will change its color instantly. You can even set the Theme which the application would use programmatically from your code.

What about Templates ?

Every control defines a ControlTemplate. A ControlTemplate defines the overall structure of the control. As I have already told you, say for instance you have a Button. Button is a control that is made up of more than one control. It would have a ContentPresenter which writes the Text over the control, it would have a Rectangle which keeps the boundary of the Button etc. So Template is a special property associated with a Control which specifies how the control will look like structurally. We can easily define our Template and change the overall structure of a control.

Templates are basically of 2 types :
  1. ControlTemplate
  2. DataTemplate

ControlTemplate defines the structure of the Control. It means say for instance, you define the ControlTemplate for a ComboBox. So from ControlTemplate you can easily change the Button associated with the ComboBox which opens the DropDown, you can change the structure of the TextBox, the Popup etc. So ControlTemplate allows you to change the overall structure of the Control.

Click To Read Entire Article
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Progress Streamed File download and Upload with Resume facility

For distributed applications, WCF is the most easy and rich component.I like to use WCF as it is very easy to implement and also provides built in functions to handle with Complex problems. One of such interesting thing that I found in WCF is the support for Streaming while sending data from the service.

WCF allows you to send Byte streams through the communication channel or even allows you to implement a service that might take the stream start location from the service call and send the stream from a certain location. It allows you to use normal HttpBinding to support streams which is capable download or upload in connected Client - Server architecture. Hence there will be not timeouts for sending or receiving large files. In this article I will show you how you could use Streaming to ensure your files are downloaded or uploaded correctly.

Once I read Demitris solution for File upload and download it made me very easy to adjust the code and enhance it further with more flexibilities.

Lets first create the service step by step :


  1. Create a Service Application and name it as WCFCommunicationService
  2. The first thing that you need to do in order to create a service is ServiceContract. So once you create a Service Library, you need to delete the existing Service1 and IService1 files from the solution and add a new Interface. 
  3. Create Two method, one for FileDownload and another for FileUpload. Lets see how the service definition looks like :

public interface IFileTransferLibrary

    void UploadFile(ResponseFile request);

    ResponseFile DownloadFile(RequestFile request);

The Contract defines the methods that are exposed to outside. The ServiceContract defines the interface which will have the members which are available to outside. The OperationContract identifies the exposed members. In the above contract the IFileTransferLibrary has two methods, UploadFile which takes an object of ResponseFile and DownloadFile which returns an object of ResponseFile.

public class ResponseFile : IDisposable
    public string FileName;

    public long Length;

    public System.IO.Stream FileByteStream;

    public long byteStart = 0;

    public void Dispose()
        if (FileByteStream != null)
            FileByteStream = null;

public class RequestFile
    public string FileName;

    public long byteStart = 0;

If you see the classes RequestFile and ResponseFile, you will see that I have used MessageContract instead of DataContract for my complex types. It is important. AS I am going to send the data streamed to the client, I need to send the data into packets. DataContract will send the whole object at a time while Messagecontract sends them into small Messages.It is also important to note that I have used IDisposable for ResponseFile to ensure that the Stream is closed whenever the connection is terminated.

Another important note is you need to use Stream as MessageBodyMember. The stream data will always transferred in MessageBody and you cannot add any other member into it. Thus you can see I have put all other members as MessageHeader.

For Both UploadFile and DownloadFile the Stream is taken from the ResponseFile object. The byteStart element of RequestFile ensures from where the the downloading should start and hence helps in Resuming a half downloaded file.  Lets see how to implement this :

public ResponseFile DownloadFile(RequestFile request)
    ResponseFile result = new ResponseFile();

    FileStream stream = this.GetFileStream(Path.GetFullPath(request.FileName));
    stream.Seek(request.byteStart, SeekOrigin.Begin);
    result.FileName = request.FileName;
    result.Length = stream.Length;
    result.FileByteStream = stream;
    return result;

private FileStream GetFileStream(string filePath)
    FileInfo fileInfo = new FileInfo(filePath);

    if (!fileInfo.Exists)
        throw new FileNotFoundException("File not found");

    return new FileStream(filePath, FileMode.Open, FileAccess.Read);
public void UploadFile(ResponseFile request)
    string filePath = Path.GetFullPath(request.FileName);
    int chunkSize = 2048;
    byte[] buffer = new byte[chunkSize];

    using (FileStream stream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
            int readbyte = request.FileByteStream.Read(buffer, 0, chunkSize);
            if (readbyte == 0) break;

            stream.Write(buffer, 0, readbyte);
        } while (true);

If you see the code, you can see how I have used byteStart to start sending Bytes for the file. This ensures the file download to have resume facility. You can also implement the same for UploadFile too.

Download FileTransfer Sample - 161KB

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Online Session on ASP.NET

I have just covered an Online session on "ASP.NET 4.0 in depth features" with Abhijit Jana for DotNetFunda.Com. If you were already there for the session, I hearty congratulate you people for your co-operation and also like you to join us in the concluding part of the session which will be declared later in the day.

In the session :

Things that we have covered already :
  1. Basic Introduction of ASP.NET 4.0 Features
  2. Visual Studio Enhancement Session
  3. Server Control Enhancements
  4. Search Engine Optimization
The session is not an end, We have lots of things to cover and probably we will fix a time later in the next week and update you the same. Stay Tune.

You can download Sample Applications that I showed : 

1. Routing Demo Application
2. Meta Tags and Parmanent Redirections

The sample video :

Download PPT, Sample Code & Video1
Download PPT, Sample Code & Video2

You can download the sample application and also run the PPT and Video from the link above. (Let me know if the link goes down.)

The Grayed items are already discussed, while others will be taken in the next session which will be announced shortly.

For reference Reading :

ASP.NET 4.0 WhitePapers

Thanks for being a part of the session.
Hope to see you soon.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

How to create a WCF service without Visual Studio

WCF is the first step in building a truly service oriented application for you. It is the most important when working with distributed architecture. The sophisticated design of WCF made me think of using it always when I need any Web service to be installed in the server. Visual Studio is capable of creating its own configuration settings that helps in developing our application with ease. But what if you don’t have Visual Studio? In this post I am going to implement one of the most basic WCF service without using Visual Studio and show you how to interact with the service. Lets do it step by step:

Server Side

Steps to create the Service definition (Contract):

  1. Open Notepad and add namespace System and System.ServiceModel. We need ServiceModel to specify a WCF service
  2. For WCF service we need to create an interface which will act as a proxy to the client.  From the client, we need to replicate the proxy object and build the same interface again. After we declare the Interface we mark the Interface with ServiceContract, and the method to be exposed to outside using OperationContract.
  3. Next we create a concrete class for the same to define the class implementing the interface.
So our server is Ready.

public interface IOperationSimpleWCF
    string MySimpleMethod(string inputText);

public class OperationSampleWCF : IOperationSimpleWCF
    public string MySimpleMethod(string inputText)
        Console.WriteLine("Message Received : {0}", inputText);
        return string.Format("Message from Server {0}", inputText);

Steps to host the service (Address , Binding):

To host the service in the server you need to know three inputs:

  1. Binding : This indicates how the service will be hosted.  For  basic soap operation with no security we need HttpBinding. We can also use other bindings as well.
  2. Address : Represents the location to host the service. When the service is hosted you can specify the qualified service path where the service will be hosted.
  3. Host the service using ServiceHost and Open the connection.
Download Sample Code - 47KB

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Partial Methods - An Uncommon Note

I think most of the people working in C# must know how Partial classes work. Partial classes allows you to divide your own class in one or more files but during runtime the files would be merged to produce a single coherent object. By this way the classes could be made very small and also easily maintainable.

The most important part of a Partial class is with designers. While you work in Visual Studio, you must have found a portion of code that is generated automatically by the designer. Designers creates a class which keeps on refreshing itself when certain modifications are made in the Designer itself. Partial classes allows you to create an alternate implementation of the same class so that the code you add to the class does not goes out when the Designer is refreshed.

Partial Methods are another new addition to .NET languages that allows you to declare / define the same method more than once. Generally Microsoft introduced the concept of Partial method to deal with Designer generated code and to allow reserving the name of a method that one needed to be implemented later in original classes. By this way, the Designer will not produce any warning without implementing the actual method, but will allow future developers to implement or write their own logic on the same method that is defined.

partial class MyPartialClass
    public void MyNormalMethod()
        Console.WriteLine("Inside first Normal Method");
    partial void MyPartialMethod(); //It is declared and will be defined later in another partial class

Let us suppose the MyPartialClass is generated by the designer. It declares the method MyPartialMethod which I have not been defined yet.

partial class MyPartialClass
    //public void MyNormalMethod()
    //    Console.WriteLine("Inside second Normal Method");
    partial void MyPartialMethod()
        Console.WriteLine("Inside second Partial Method");

In another implementation of MyPartialClass, I have defined the method MyPartialMethod which holds the actual implementation of the code. So if I create an object of MyPartialClass, it will hold both method MyNormalMethod and MyPartialMethod and when it is called it calls appropriately.

Another thing to note, the implementation of Partial method is not mandatory.  If you do not define the partial method in another partial class, it will eventually be eliminated completely in runtime IL.

Limitations of a Partial Method :

  1. Partial Method is by default private. Hence you can only call a partial method from within the partial class. 

    partial class MyPartialClass
        public void MyNormalMethod()
            Console.WriteLine("Inside first Normal Method");
        partial void MyPartialMethod(); //It is declared and will be defined later in another partial class
    Thus even if you do not declare the method MyPartialMethod, you can even call it from within the class. During runtime, CLR will automatically call if it is implemented or will eliminate the call completely from the system.
  2. Partial Method needed to be declared inside a Partial class. A partial class is only capable of redefining the part later in another file. So it is essential to mark the class as partial as well when it have a partial method.
  3. Cannot be marked as extern.
  4. Must have a void return type and also cannot use out parameter as argument.
  5. Partial method does not allow to write as virtual, sealed, new, override or extern.

Since partial method is created to generate methods in designer, most of the designer highly using partial methods. Even though it  is very rarely used in real life, it would be worth if you know about it.  

For further reference:

C# 3.0 Partial Method - What Why and How

Thank you for reading my post.
    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    Marble Diagrams and Rx

    Today I am going to discuss how to draw Marble Diagrams. I just came across with it in Reactive Framework. In Channel 9 videos, Jeffrey Van Gogh shows how to get started with Rx. Ever since I look deep into it, I find it very interesting, and perhaps a new way of thinking or understanding for Asynchronous programming structure. Reactive Framework introduces a few operators, which you might apply to an Observable to get the resultant observable. The way to represent each of these attributes can be done using Marble Diagrams. 

    Before you start dealing with Reactive Framework, it is good to start with IObservable and IObserver. I have already introduced with these two interfaces which are the building block for the Reactive Framework. You can read these articles before going through with Marble Diagrams.

    How to create Marble Diagram. 

    Marble diagram is basically a way to represent the Rx operations. You may think a marble diagram to be a pictorial representation of different operators that is defined with Reactive Framework. Lets look how to create a Marble Diagram : 

    So in the sample image you can see we measure Time in X-Axis while operations on Y-axis. Say for instance, you have an Observable which is represented by the first horizontal line. The small circles represents OnNext calls of IObserver. If you know already read about Observable and Observer, you might already know that each Observer has OnNext method, which gets invoked whenever the observer changes its state.  Hence, in our case the observer invokes a function f() to get to the new State.  The | represents the OnComplete for the Observer. So after OnComplete, the Observer will stop observing states.

    We represents OnError using X in a marble diagram. In case of an Observable, OnError and OnComplete produces the end  point for the observer. So Here after executing the two OnNext if the Observer encounters with an Exception, OnError gets invoked and the Observer will terminate. 

    So on the first image, we execute the function f() to get the new state with the Buttom Line. Now on, I am going to create a few Marble Diagrams, to make your understanding clear. 


    SelectMany is very easy to explain. Say you have two or more Observers. In this case, SelectMany will eventually invoke all the OnNext of each observer. 

     So if you have 3 observers, the SelectMany will produce Observer which aggregates all of them. 

    int[] collection = { 2, 5, 5, 6, 2, 4 };
    int[] collection2 = { 1, 4, 2, 1, 5, 6 };
    var ob1 = Observable.ToObservable(collection);
    var ob2 = Observable.ToObservable(collection2);
    var ob3 = ob1.SelectMany(ob2);
    //var ob3 = ob1.Select(r => r + 2);
    var disp = ob3.Subscribe(r => Console.WriteLine("OnNext : {0}", r.ToString()), 
                                r => Console.WriteLine("Error : {0}", r.ToString()), 
                                () => Console.WriteLine("Completed"));
    So the Observer will select from each of the Observer and get you the output.

    In case of an error, the final Observer will stop when first error of any Observer is encountered.

    SkipUntil / SkipWhile

    SkipWhile and SkipUntil works in opposite. Say for instance, you have two Observable. SkipUntil gives you OnNext for each of them until the OnNext from the other observer is received. On the contrary, SkipWhile will produce OnNext for the Observer while the OnNext from the second observer is Received. When the second observer is Complete or gives an error, the final observer will terminate in case of SkipWhile.

    So in the above diagrams, you can see While will bypass all the values until the second observer receives an entry.

    Further Reference

    To learn the operators of Marble Diagrams, you can see the latest Videos on Channel 9. Here is a few more Operators :
    I hope this will help you to understand the Marble Diagrams, and hope these will describe you some more operators of Rx Framework.
    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    Taskbar with Window Maximized and WindowState to None in WPF

    Say you want your WPF  application to have no Title bar, and will maximized to Full Screen, what you first think of. Its the most easiest to do.

    1. Set WindowStyle to Maximized : By this the Window will not show up any title bar. The window style will be transformed to a Box with border in it. 
    2. Set WindowState to None :  By this the window will be maximized to the whole screen and will show only the window and nothing else..

    Oh.. Hold on ..Hold on... As I say, it hides the whole screen, it means it even will not show up the Taskbar or any external gadgets applied to your desktop if it is not set to Always on Top attribute to it.

    Yes, this is the problem that I faced recently, when people wanted me to show the TaskBar even though the application should be Maximized.

    Is it a Bug ? 

    If I am not wrong, WPF builds application based on the Screen Resolution. It produces DPI independent pixels. If you specify it to be full screen, it first gets the Resolution of the screen, and draws the pixel based on its own algorithm. Hence, when you specify it to Maximized, it takes up the whole screen, as otherwise some portion of the screen will be hidden outside the range of the boundary.

    When you restore a WPF screen, it will also recalculate the work area based on the distance between the resolution boundaries and resize itself accordingly. No do you think Microsoft should really have an alternative state which show up the Taskbar as it does with normal windows ? I think yes.

    The Solution

    As I needed to do this, I have just tried out few workarounds to this myself.

    Following Lester's Blog on this issue, I have to use

    private static System.IntPtr WindowProc(
            System.IntPtr hwnd,
            int msg,
            System.IntPtr wParam,
            System.IntPtr lParam,
            ref bool handled)
        switch (msg)
            case 0x0024:
                WmGetMinMaxInfo(hwnd, lParam);
                handled = true;
        return (System.IntPtr)0;
    private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
        MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
        // Adjust the maximized size and position to fit the work area of the correct monitor
        int MONITOR_DEFAULTTONEAREST =0x00000002;
        System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
        if (monitor != System.IntPtr.Zero)
            MONITORINFO monitorInfo = new MONITORINFO();
            GetMonitorInfo(monitor, monitorInfo);
            RECT rcWorkArea = monitorInfo.rcWork;
            RECT rcMonitorArea = monitorInfo.rcMonitor;
            mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
            mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
            mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
            mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
        Marshal.StructureToPtr(mmi, lParam, true);

    The call to API WmGetMinMaxInfo gets you the size of Maximize window for the current desktop.

    internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO   lpmi);
    internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

    The call to GetMonitorInfo gets you a MONITORINFO object and if you see the code carefully it actually position the window in such a way that it absolutely resize itself to the height and width of the rectangular area.

    To call this method, I can use SourceInitialized event which will eventually be called whenever the WindowState is modified.

    void win_SourceInitialized(object sender, EventArgs e)
        System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
        WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));

    Sounds good ?
    Oh.. Lets give another easier solution that I have used. Its very simple.

    Set properties for your window :


    And go to your code and just resize your window based on PrimaryScreen width and height. Also make sure you do set the Left and Top of the window as well.

    this.Width = System.Windows.SystemParameters.WorkArea.Width;
    this.Height = System.Windows.SystemParameters.WorkArea.Height;
    this.Left = 0;
    this.Top = 0;
    this.WindowState = WindowState.Normal;

    Making WindowState.Normal will ensure that the default behaviour of the window is overridden and also makes the Taskbar Reappear.

    I have included my sample application :

    Have fun.

    Download Sample - 38KB
    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    .NET Community Session : ASP.NET 4.0 In - Depth

    I am going to speak on a Community Session Organized by DotNetFunda on ASP.NET 4.0 with Abhijit Jana.

    ASP.NET 4.0 comes with lots of new features that enhance the developers to deal with ASP.NET applications easily and also core functionality to deal with both server side and client side of an ASP.NET application. These changes makes ASP.NET 4.0 applications more effective than the existing ASP.NET applications.

    The Agenda for the Session :
    (Click to enlarge to Full Size)

    • What’s New in ASP.NET 4.0
    • Improvement in Visual Studio 2010 for web development
    • Empty Website project and Cleaner Web.Config
    • MetaKeyword and MetaDescription enhancements
    • Controlling ViewState mechanism 
    • Controlling ClientID generation for asp.net controls
    • CompressionEnabled Session
    • CSS Improvements and CSS Friendly Menu Control
    • ListView rendering mechanism, Enhancement in Listview control
    • Enhancement in RadioButtonList and CheckBoxList
    • SEO Friendly URL (Web Form Routing)
    • Permanent Redirection mechanism
    • Improvements in Code Expressions
    • Overview of Dynamic data
    • Caching mechanism (Output Caching, Object caching etc.)
    • ASP.NET Applications / Database deployment.
    • Q & A
    • Summary
    Speakers: Abhishek Sur & Abhijit Jana

    Scheduled Date: 19-Sep-2010 (Sunday )

    Scheduled Time: 2.00 PM to 4.30 PM

    Live meeting URL:  https://www.livemeeting.com/cc/mvp/

    Meeting ID:  Will be sent to your email id before the session scheduled date and time.

    Is Paid?: No, It’s FREE Session

    Is Registration required ? Yes . Please register here http://bit.ly/d6aVYM .

    Disclaimer : http://www.abhisheksur.com/p/disclaimer.html
    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    Use of Expression Trees in .NET for Lambda Decomposition

    Expressions are the building block of any Lambda Expression. In C# 3.0, .NET framework has introduced a new technique to make use of Anonymous methods a better way. The "Little Gem" LINQ, uses Lambda expression extensively to invoke filter statements to IEnumerable objects and hence making the life for a programmer very easy. Simple lambda expressions like

    x => x<5 

    may come very handy as we do not need to define a method extensively for such a small purpose. C# also introduced a couple of Generic delegates like Func<...>, Action<...> etc. in Base Class Library which lets you to pass any type of argument to a method body. The one with Func are for methods which require something to return while ones with Action dont need to return anything.

    To learn more about LINQ please have a quick pick on my article on LINQ and Lambda Expressions.But if you have already read about the basics of LINQ, it is not all that is needed. Lambda expressions are cool and extensive use of Anonymous methods are truly awesome, but basically when I think of using Lambda Expression in my own application, I always think of extending the Lambda expressions a bit further so that I could use it dynamically during runtime and later on compile them to produce the actual anonymous delegates. In this article I will put forward the story of Linq and Lambda Expressions further and introduce you with Expression Trees and also show you to create Expression Trees dynamically during runtime.

    What is an Expression Tree?

    Simply speaking, an expression tree is nothing but the representation of a Lambda Expression in terms of .NET objects. The Expression is the main class that holds any expression in it and it lets us to divide the whole body of the Expression into smaller individual units. For instance : 

    Func<int, bool> mydelegate = x => x < 5;
    Expression<Func<int, bool>> myexpressiondelegate = x => x < 5;

    In the above code the delegate Func can take the expression x=>x<5 which represents an anonymous method that takes an integer argument and returns if the value is less than 5.
    Download Sample - 38 KB

    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    Notion of System.Nullable - A Look

    I love C# as a language. It has lots of flexibilities and hooks to turn around things that was impossible for other languages. One of such thing is the introduction of Nullable Types. In this post,  I will discuss how you could use Nullable to make sure your code works well for null values in Value Types.

    Why System.Nullable?

    You must already know, System.Nullable is the only structure that supports the storage of Null as a valid range of values. Generally in case of structures it cannot store null values in it. Say for instance :

    Int32 is a structure. When you specify
    int x;

    It will automatically assign 0 to x. This is same as
    int x = default(int);

    Generally structures always recursively call default to initialize the value of it. Say for instance :

    struct MyCustomStructure
         public int m;
         public int n;

    I have defined a custom structure MyCustomStructure. If you declare an object of it like :
    MyCustomStructure myobj;

    It will assign myobj to its default. You cannot assign null to myobj. The only way out to this situation is Nullable.

    MyCustomStructure myobj = null; //throws exception
    Nullable<MyCustomStructure> myobj = null; //works fine

    Hence you can see, you should always use Nullable for a structure if you want to store the value of null to a structure. For data centric applications, we generally need to keep a variable out of the scope of valid values so that the variable can have a value which might identify the value as nothing. Null is taken as nothing, but in case of normal structures it does not allow us to do that. If you store nothing to an integer, it will automatically initialize to 0. But for any application 0 might be a valid value. So you cannot exclude the 0 from the range of data. Hence you need Nullable to workaround this issue.

    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    Author's new book

    Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
    Grab it now !!!