tags:

views:

143

answers:

2
+1  Q: 

Nullable class?

I have this class

public class FilterQuery
    {
        public FilterQuery() { }

        public string OrderBy { set; get; }
        public string OrderType { set; get; }        

        public int? Page { set; get; }
        public int ResultNumber { set; get; }

    }

I would like to use it like this

public IQueryable<Listing> FindAll(FilterQuery? filterQuery)

Is this possible?

Thanks

+16  A: 

This immediately begs the question of why. Classes are by definition reference types and thus are already nullable. It makes no sense to wrap them in a nullable type.

In your case, you can simply define:

public IQueryable<Listing> FindAll(FilterQuery filterQuery)

and call FindAll(null) to pass no filter query.

If you're using C#/.NET 4.0, a nice option is:

public IQueryable<Listing> FindAll(FilterQuery filterQuery = null)

which means you don't even have to specify the null. An overload would do the same trick in previous versions.

Edit: Per request, the overload would simply look like:

public IQueryable<Listing> FindAll()
{
    return FindAll(null);
}
Noldorin
I see... but the thing is that I have relatively complex method and if I make overload I will duplicate whole method?
ile
@ile: Not at all, see my updated post.
Noldorin
I get it, thank you Noldorin!
ile
Was glad to help clarify.
Noldorin
+5  A: 

There's no need to do that; all class types are reference types, which means that it is nullable by definition. Indeed, there is no way to enforce that it's non-null at compile time.

The Nullable<T> struct is designed to allow value types (which are, by definition, not null) to represent a null value.

It's also worth noting that the ability to compare Nullable<T> with null (or Nothing in VB.NET) is syntactic sugar; because Nullable<T> is a struct, it cannot actually be null. In the case where it represents a null value, HasValue is false and Value is default(T).

Adam Robinson
You can enforce non-null condition at compile time by using assertions and formal verification. There is a built-in tool in Visual Studio 2008/10, if you install the Microsoft "Code Contracts" extension. But formal (static) verification works only if every part of your code is well asserted, and if your condition does not depend on a runtime one. Simpler : formal verification does not work.
Aurélien Ribon