How will a C# switch statement’s default label handle a nullable enum?

If it’s null, it will hit the default label. public enum YesNo { Yes, No, } public class Program { public static void Main(string[] args) { YesNo? value = null; switch (value) { case YesNo.Yes: Console.WriteLine(“Yes”); break; case YesNo.No: Console.WriteLine(“No”); break; default: Console.WriteLine(“default”); break; } } } The program will print default. Unless null is … Read more

What are lifted operators?

Lifted operators are operators which work over nullable types by “lifting” the operators which already exist on the non-nullable form. So for example, if you do: int? x = 10; int? y = 10; int? z = x + y; That “+” operator is lifted. It doesn’t actually exist on Nullable<int> but the C# compiler … Read more

Optional return in C#.Net

Not in the language, no, but you can make your own: public struct Optional<T> { public bool HasValue { get; private set; } private T value; public T Value { get { if (HasValue) return value; else throw new InvalidOperationException(); } } public Optional(T value) { this.value = value; HasValue = true; } public static … Read more

Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?

Because string type’s null really points to nothing, there isn’t any object in memory.But int? type(nullable) even with value set to null still points to some object.If you read Jeffrey Richter’s “CLR via C#” you’ll find out that nullable type are just facade classes for common types with some incapsulated logics in order to make … Read more

Linq query with nullable sum

You want to use the nullable form of Sum, so try casting your value to a nullable: from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select v.Points).Sum(r => (decimal?) r.Points) } Your issue is discussed here in more detail: http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx

How to compare nullable types?

C# supports “lifted” operators, so if the type (bool? in this case) is known at compile you should just be able to use: return x != y; If you need generics, then EqualityComparer<T>.Default is your friend: return !EqualityComparer<T>.Default.Equals(x,y); Note, however, that both of these approaches use the “null == null” approach (contrast to ANSI SQL). … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)