0 Comments
  • Posted in:
  • C#

I was answering SO questions and someone asked how to null guard stuffs when calling a property or a method of something that might be null.

I mentioned that C# 6 provides a way to do this by allowing you to use the following syntax: foo?.bar?.baz which will prevent the code from parsing the rest and erroring out once a null is encounter anywhere in the method / property chain which it is called null-propagation.

So, an idea popped in my mind since C# 6 is not quite there yet, how can we do this in C# 5?  After some thinking, I came up with the idea of using lambda expression combined with extension method and some generic magic that I think might work and came up with the following syntax: foo._(_=>_.bar)._(_=>_.baz)  that seems to work okay.

The implementation is like so:

public static class ObjectExtension
{
    //Probably not a good idea to name your method _, but it's the shortest one I can find, I wish it could be _?, but can't :(
    public static K _<T, K>(this T o, Func<T, K> f) 
    {
        try 
        {
            var z = f(o);
            return z;            
        }
        catch(NullReferenceException nex) 
        {
            Trace.TraceError(nex.ToString());
            return default(K);
        }
        
    }
}


The running example can be found below:

0 Comments

Was strolling around StackOverflow and came to a question #1118232.  Where this guy was asking how come you can create a class inheriting from another generic class like so:

class Person : EntityBase<Person>
{
 //Whatever here...
}

He said it’s like the chicken and egg problem :)  Which I sort of agree.  After pondering on the thing for a bit, I tried mucking around with it in Visual Studio and came up with this that I think sort of give me a bit more clarification on the idea, but not by much… Still trying to find when I need to really use something like this.   And the code that I came up with is this:

class Program
    {
        static void Main(string[] args)
        {
            var wife = new Human(Gender.Female);
            var baby = wife.GiveBirth();
            Console.WriteLine(baby.Gender);
 
            Console.ReadKey();
        }
    }
 
    class CanGiveBirthTo<T> where T : new()
    {
        public CanGiveBirthTo()
        {
        }
 
        public T GiveBirth()
        {
            return new T();
        }
    }
   
    class Human : CanGiveBirthTo<Human>
    {
        public Gender Gender { get; private set; }
 
        public Human(Gender gender)
        {
            Gender = gender;
        }
 
        public Human()
        {
            Gender = RandomlyAssignAGender();
        }
 
        Gender RandomlyAssignAGender()
        {
            var rand = new Random();
            return (Gender) rand.Next(2);
        }
    }
 
    enum Gender
    {
        Male = 0,
        Female = 1
    }

I don’t know if this is of any use to anyone…, but enjoy… LoL.

Any idea what sort of real application code that could fall into this pattern in real project?

0 Comments

I blogged not too long ago about some stuffs that I was pondering

Finally found out how one can get the Object of type ‘System.Decimal’ cannot be converted to type ‘System.Int32’ error.

Given this code:

using System;   
  using System.Data;   
  using System.Data.SqlClient;   
  using System.Collections.Generic;   
     
  namespace ConsoleApplication1   
  {   
      public class Foo   
      {  
          public int Id { get; set; }  
          public int Number { get; set; }  
      }  
    
      class Program  
      {  
          static void Main(string[] args)  
          {  
              var foos = new List<Foo>();  
              var fooType = typeof(Foo);  
    
              using (var cn = new SqlConnection(@"Server=.\SQLEXPRESS;Database=JimmyTest;Integrated Security=true"))  
              {  
                  using (var cmd = cn.CreateCommand())  
                  {  
                      cmd.CommandText = "SELECT * FROM dbo.[tablea] a INNER JOIN dbo.[tableb] b ON a.[BId] = b.[Id]";  
                      cmd.CommandType = CommandType.Text;  
    
                      cn.Open();  
    
                      using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))  
                      {  
                          var fieldCount = reader.FieldCount;  
    
                          while (reader.Read())  
                          {  
                              var foo = new Foo();  
    
                              for (var i = 0; i < fieldCount; i++)  
                              {  
                                  var property = fooType.GetProperty(reader.GetName(i));  
                                  if (property != null)  
                                  {  
                                      property.SetValue(foo, reader.GetValue(i), null);  
                                  }  
                              }  
                              foos.Add(foo);  
                          }  
                      }  
                  }  
              }  
    
              Console.ReadLine();  
          }  
      }  
  }

And this database:

USE master
GO

CREATE DATABASE JimmyTest
GO

USE JimmyTest
GO

CREATE TABLE tablea (Id int, BId int, Number int)
GO

CREATE TABLE tableb (Id int, Number decimal(10,2))
GO

INSERT INTO tablea VALUES(1, 1, 100)
INSERT INTO tablea VALUES(2, 2, 50)
GO

INSERT INTO tableb VALUES(1, 33.33)
INSERT INTO tableb VALUES(2, 15.23)
GO

Can you spot the bug?

Found it in the wild while troubleshooting one of my clients’ code.

Hint: Greed is one of the seven deadly sins.  It’s pure evil!

0 Comments
public class CallToAction
{
    abstract class CSharpDeveloper { }
    class You : CSharpDeveloper { }
    string ReadTheContentOf(System.Uri url) { return string.Empty; }
    System.Uri URL = new System.Uri("http://stackoverflow.com/questions/9033/hidden-features-of-c");

    public CallToAction()
    {
        var you = new You();

        if (you is CSharpDeveloper)
            ReadTheContentOf(this.URL).AndLearnTonsOfStuffs();
    }
}

public static class MyExtensions
{
    public static void AndLearnTonsOfStuffs(this string input) { }
}

emoticon

”This compiles by the way.  It won’t do squat, but it compiles!!

Go spend half a day or a day and read that post, all the answers, the comments and the links within it.  I promised you won’t regret it and you might actually learn a thing or two about C# that you don’t know about.  I know I did.

Hint: the URL in the code above is actually clickable if you didn’t notice.  Or if you are hyperlink-challenged, you can cut and paste the following URL to your browser:
http://stackoverflow.com/questions/9033/hidden-features-of-c

Enjoy…

emoticon

0 Comments

When you use .NET Activator.CreateInstance to create a new object of a certain type, make sure you reference the Project / DLL that contain the type definition or load it manually somehow to an AppDomain.  Otherwise your call will fail. Say you have the following solution:

Solution Foo
    Project Bar1
        IUser
        IDataMapper
          IUser Load(...);
    Project Bar2 (references Bar1)
        ADSpecificDataMapper : Bar1.IDataMapper
          IUser Load(...) { ... }
    Project Bar3
       User : IUser
          IDataMapper m_Mapper = Settings.Instance.UserMapper
          IUser Load(...) { return m_Mapper.Load(...) }
    Project Baz (references Bar1)
        Settings
           Settings Instance = new Settings() //singleton
           IDataMapper Mapper = CreateMapper(ConfigurationManager.AppSettings[...])
           IDataMapper CreateMapper(SpecificMapperClassNameFromAppConfig)
    Project ConsoleTester (references Baz, Bar3)
       Main
          IUser user = User.Load(...);

Note that ConsoleTester is not referencing Project Bar2 (which contain the ADSpecificDataMapper that will be created through the Factory Method CreateMapperin Baz.Settings class.  This will cause it to fail.  Adding Bar2 to the ConsoleTester project reference will remedy the problem.