DisplayAttribute ignored? (um, no.)

February 7, 2014

To make full use of unobtrusive validation, I added the necessary attributes (DisplayAttribute, validation) to the models used in an MVC application.

However, one member of a model class did not retrieve the LabelFor text from the defined resource file, and I could not find the cause for this behavior.

After staring at the relevant code for several looong minutes, it struck me: the member was defined as field, rather than a property, missing the typical { get; set; }

I wish there was an attribute [AllPublicMembersMustBeProperties] which would cause the compiler to raise in error in such cases.

Just dreaming… ūüėČ


C# Wishlist: Non-nullable Reference Types

January 17, 2014

When I started my C# Wishlist series, one wish, though never published, was to introduce non-nullable reference types in C#.

Everybody who has written the lines

public class C
{
  public C (T somearg)
  {
    if (somearg == null)
      throw new NullArgumentException("somearg");
    ...
  }
}

several thousand times would appreciate this language feature. (as Yann’s comment on a Jon Skeet blog post illustrates)

Now, a couple of years later, Eric Lippert read my mind, and answers why the (consistent!) implementation of this feature is not as trivial as it sounds.

Workaround for the time being: Code Contracts (.Net 4 and above) or external libraries such as CuttingEdge.Conditions.


SQL Server Wishlist

March 4, 2013

Occasionally I write about my (and others’) wishes for future versions of C#.

Recently I came across the website of Erland Sommarskog, and besides great articles about various aspects of SQL Server, he also maintains a wishlist for SQL Server.

Enjoy ūüėČ


Response to “C# Wishlist: Null-Safe Dereferencing”

November 22, 2012

Reader Alex D commented on one of my C# Wishlist posts providing more elaborate code on this topic.

However, WordPress loves to eat angle brackets found in comments, leaving mangled code. I tried to restore the original code which probably looked like this:

public static TOut NullSafe<TIn, TOut>(this TIn obj, 
    Func<TIn, TOut> memberAction)
    where TIn : class
    where TOut : class
{
    return !ReferenceEquals(obj, null) ? memberAction(obj) : null;
}

public static TOut NullSafe<TIn, TOut>(this TIn? obj, 
    Func<TIn, TOut> memberAction)
    where TIn : struct
    where TOut : class
{
    return obj.HasValue ? memberAction(obj.Value) : null;
}

// If the return type of the lambda is not a nullable type but a value type
// you should write a cast to nullable in the lambda

public static TOut? NullSafe<TIn, TOut>(this TIn obj, 
    Func<TIn, TOut> memberAction)
    where TIn : class
    where TOut : struct
{
    return !ReferenceEquals(obj, null) ? memberAction(obj) : (TOut?)null;
}

public static TOut? NullSafe<TIn, TOut>(this TIn? obj, 
    Func<TIn, TOut> memberAction)
    where TIn : struct
    where TOut : struct
{
    return obj.HasValue ? memberAction(obj.Value) : (TOut?)null;
}

// Or use the following functions
// Unfortunately, they are named differently because the compiler doesn't allow
// overloads that differ only in their generic type constraints

public static TOut? NullSafeV<TIn, TOut>(this TIn obj, 
    Func<TIn, TOut> memberAction)
    where TIn : class
    where TOut : struct
{
    return !ReferenceEquals(obj, null) ? memberAction(obj) : (TOut?)null;
}

public static TOut? NullSafeV<TIn, TOut>(this TIn? obj, 
    Func<TIn, TOut> memberAction)
    where TIn : struct
    where TOut : struct
{
    return obj.HasValue ? memberAction(obj.Value) : (TOut?)null;
}

C# Wishlist: Methods returning Anonymous Types

January 29, 2012

Anonymous Types were introduced in .Net 3.5, and I believe the motivation was to support the Linq Select() method which implicitly creates new types based on existing types (i.e. database-based classes) in statements like

var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

This statement creates a strongly-typed read-only variable (productQuery) and an anonymous type with the properties Color and Price, based on the Product definition generated by the database OR mapper.

However, as stated in the linked article, these types cannot be passed as parameters or declared as return types of methods or delegates, unless variables of these types are cast to object.

In my opinion, however, the restriction on return types could easily be remove if some requirements are met. Just imagine two methods like these:

public var GetProducts()
{
    var productQuery = 
        from prod in products
        select new { prod.Color, prod.Price };
    return productQuery.ToList();
}

public var GetProduct(int productId)
{
    var productQuery = 
        products
        .Where(prod => prod.productId)
        .Select(prod => new { prod.Color, prod.Price })
        .FirstOrDefault(); 
    return productQuery;
}

As with the Linq examples, these examples are again shortcuts avoiding explicit type declarations. The result is still strictly typed, but some restrictions remain:

  • if more than 1 return statement occurs, all return statements need to declare the same properties of the return type
  • no return statement may explicitly return null
  • the accessibility level of the returned type is the same as that of the declaring method

The question of returning anonymous types is usually regarded a closely related to Tuples introduced in .Net 4.0. The major drawback of tuples, as I see it, is that the Tuple’s properties are named Item1, Item2, etc without any possibility to give them useful or sensible names, other than declaring your on class. The feature seems confusing and already raised some questions on SO.

Tuples and anonymous return types allow another food for thought: the request to have syntactic support for tuples just as sketched by Miguel de Icaza in Mono (I don’t know whether it is included in released code). His example in C# is

(user, password, host, port, path) = ParseUri (url);

calling a method

Tuple<string, string, string, int, string> ParseUri (string url);

Using anonymous types, the method might as well be declared as

var ParseUri(string url)
{
    return new { User = "...", Password = "...", 
        Host = "www.example.com", Port = 80, Path = "/..." };
}

and invoked by

var parsedUri = ParseUrl("http://www.example.com/");

One can easily see that these methods (tuples and anonymous types) could be used interchangeably.

Personally, I find the tuple notation using round parens (as in Perl, Python) untypical for C#, which uses curly braces { } for structured data.

 


C# Wishlist: Null-Safe Dereferencing

January 19, 2012

During tests of a web application I came across a runtime error cause by the line:

var startUrl = Request.UrlReferrer.AbsoluteUri;

From within the application, the line works fine. However, if you paste the current URL into the address bar and hit Enter, it will cause a NullReferenceException. The obvious solution is to rewrite as

string startUrl = null;
if (Request.UrlReferrer != null)
    startUrl = Request.UrlReferrer.AbsoluteUri;

Suddenly I *knew* I wanted that null-safe dereferencing operator everybody is talking about:

Personally I prefer the ?. notation to -> or ??? I found elsewhere:

var startUrl = Request?.UrlReferrer?.AbsoluteUri;

This answer on SO illustrates a solution that is currently possible, but a bit verbose for my taste:

R NotNull<T, R>(this T src, Func<T, R> f)
      where T : class
      where R : class 
{
    return src != null ? f(src) : null;
}

The class constraint on R is not necessary if you replace null with default(R):

R NotNull<T, R>(this T src, Func<T, R> f)
      where T : class 
{
    return src != null ? f(src) : default(R); 
}

Virtual Static Interface Methods in C# – Introduction

August 23, 2011

For quite some time now I wanted to blog about a feature I missed in C# for a long time, what I used to call static interfaces or static class interfaces.

In a class definition you can always add static properties and methods. In my opinion, these static elements really are elements of¬† a separate class which acts as a “StaticClass” for the original class. For example, a framework might need to operate on static methods defined by such “StaticClasses” depending on the type of a parameter passed to the framework.

Pseudo Code:

static interface IStaticClass
{
    void DoSomething();
}
class Foo : IStaticClass
{
    public static virtual void DoSomething()
    {
        Console.WriteLine("hello from Foo");
    }
}
class Bar : IStaticClass
{
    public static virtual void DoSomething()
    {
        Console.WriteLine("hello from Bar");
    }
}
class FooEx : Foo
{
    public static override void DoSomething()
    {
        Console.WriteLine("hello from FooEx");
    }
}
void Main()
{
    Bar bar = new Bar();
    Foo foo = new FooEx();

    // magic happens here:
    (bar.GetType() as IStaticClass).DoSomething();
    foo.class.DoSomething();
}

Of course I know that this is not possible in C#, and my personal impression is now that such a solution (or the desire to have such a solution) would clearly be an indication of bad design.

One reason for this indication is that there is a fundamental difference between virtual methods and static methods:

Static methods are statically identified by Namespace + Class name + Method name + Parameter types.

Virtual methods are dynamically identified by Method name + Parameter types of the Virtual Method Table of the Class definition (Namespace + Class name), optionally implementing an Interface definition (Namespace + Interface name), of an instantiated object.

I am not alone, though. A quick search on StackOverflow to research for these blogs came up with a quite a lot of questions:

The next two blogs illustrate a solution using techniques already available in C#.